add a tag to each div using jQuery

This is the current code:

  <div class="main-wrap">
    <div class="inner-wrap">
        some content here
        <span>
           <a href="1">test1</a>
        </span>
    </div>

    <div class="inner-wrap">
      some content here
      <span>
        <a href="2">test2</a>
      </span>
    </div>

    <div class="inner-wrap">
      some content here
      <span>
         <a href="3">test3</a>
     </span>
    </div>
 </div>

I need to fetch the href attr of a tag within span tag and insert it to the whole inner-wrap element. Something like this:

  <div class="main-wrap">
    <div class="inner-wrap">
      <a href="1">
        some content here
        <span>
           <a href="1">test1</a>
        </span>
      </a>
    </div>

    <div class="inner-wrap">
     <a href="2">
      some content here
      <span>
        <a href="2">test2</a>
      </span>
     </a>
    </div>

    <div class="inner-wrap">
     <a href="3">
      some content here
      <span>
         <a href="3">test3</a>
     </span>
    </div>
   </a>
 </div>

I can fetch the href tag of each a tag but I'm confuse as to how to append it to the each inner-wrap divs. This is what I've done by far:

$('.inner-wrap').each(function(){
    $this = $(this);
    $fetchLink = $this.children('span').find('a').attr('href');
    console.log($fetchLink);
});

I know this is really very simple but I can't get to work around. Can someone please help?

here's working jsfiddle

Answers 1

  • You can use wrapInner(), However, You should not nest anchor inside another anchor element.

    $('.inner-wrap').wrapInner(function(i) {
      var $this = $(this);
      var a = $this.children('span').find('a');
      var href = a.attr('href');
    
      //Remove inner anchor
      a.replaceWith(a.text());
    
      return "<a href='" + href + "'></a>";
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="main-wrap">
      <div class="inner-wrap">
        some content here
        <span>
               <a href="1">test1</a>
            </span>
      </div>
    
      <div class="inner-wrap">
        some content here
        <span>
            <a href="2">test2</a>
          </span>
      </div>
    
      <div class="inner-wrap">
        some content here
        <span>
             <a href="3">test3</a>
         </span>
      </div>
    </div>


Related Articles