Home > Software engineering >  Using .each function to take a value, then edit and put the result in other objet propery
Using .each function to take a value, then edit and put the result in other objet propery

Time:12-21

I'm trying to make a script that take the URL of the "img src" then edit and finally put it on "a data-title= href", all them on each "item-foo item-bar item-foo bar" The edition works and I get the link but then I can't make the change I Try to do an "each" inside another "each" but it doesn't work, next try to return with the variable "video" but only the last one comes out.

I hope to explain myself well, English unfortunately is not my native language and on top of that I am learning javascript by kicks haha. My regards and respects.

I hope to explain myself well, English unfortunately is not my native language and on top of that I am learning javascript by kicks haha. My regards and respects!

<div >

  <div >

    <a data-title="" href="https://example.com/news/16143-chair.htm" title="Chair with rotten legs">
      <span >
<img src="https://thumbs.example.com/thumbs/v/i/d/e/o/chair38630.mp4/chair38630.mp4-3.jpg" alt="Chair with rotten legs" />
            </span>
    </a>
  </div>

  <div >
    //similar content, diferent URLs
  </div>

  <script>
    jQuery("span.image img").each(function() {

      direccion = $(this).prop("src");
      edit1 = direccion.replace("thumbs", "media");
      edit2 = edit1.replace("thumbs", "videos");
      index = edit2.indexOf("mp4");
      video = edit2.slice(0, index   3);

      //console.log("The URL of the video is: "   video);

    });
  </script>

CodePudding user response:

To find the containing <a> you can use .closest('a') and then set the .attr()

jQuery("span.image img").each(function() {
  direccion = $(this).prop("src").replace("thumbs", "media").replace("thumbs", "videos");
  $(this).closest('a').attr('href',direccion.slice(0, direccion.indexOf("mp4")   3));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >

  <div >

    <a data-title="" href="https://example.com/news/16143-chair.htm" title="Chair with rotten legs"> Right click and check href
      <span >
<img src="https://thumbs.example.com/thumbs/v/i/d/e/o/chair38630.mp4/chair38630.mp4-3.jpg" alt="Chair with rotten legs" />
            </span>
    </a>
  </div>

  <div >
    <!--similar content, diferent URLs-->
  </div>

  • Related