Home > Software design >  How to wrap the elements within the parent in jQuery
How to wrap the elements within the parent in jQuery

Time:10-06

By using jQuery, how do I wrap the <a> tags in a <p> tag within the parent div.

I don't have any control on HTML to add unique classes. Please help, Thanks..

My Current HTML:

<div class="content">
    <a href="#" class="anchor">some anchor link</a>
    <a href="#" class="anchor">some anchor link</a>
    <p>some paragraph content</p>
</div>
<div class="content">
    <a href="#" class="anchor">some anchor link</a>
    <a href="#" class="anchor">some anchor link</a>
    <p>some paragraph content</p>
</div>

My current jQuery:

$( ".anchor" ).wrapAll( "<p class='new'></p>" );

My Current Output:

<div class="content">
  <p class="new">
    <a href="#" class="anchor">some anchor link</a>
    <a href="#" class="anchor">some anchor link</a>
    <a href="#" class="anchor">some anchor link</a>
    <a href="#" class="anchor">some anchor link</a>
  </p>
  <p>some paragraph content</p>
</div>
<div class="content">
  <p>some paragraph content</p>
</div>

But I want output like this:

<div class="content">
  <p class="new">
    <a href="#" class="anchor">some anchor link</a>
    <a href="#" class="anchor">some anchor link</a>
  </p>
  <p>some paragraph content</p>
</div>
<div class="content">
  <p class="new">
    <a href="#" class="anchor">some anchor link</a>
    <a href="#" class="anchor">some anchor link</a>
  </p>
  <p>some paragraph content</p>
</div>

CodePudding user response:

You need .each from the content level

$(".content").each(function() {
  $(this).find(".anchor").wrapAll("<p class='new'></p>");
})
.new  { background-color: grey }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
  <a href="#" class="anchor">some anchor link</a>
  <a href="#" class="anchor">some anchor link</a>
  <p>some paragraph content</p>
</div>
<div class="content">
  <a href="#" class="anchor">some anchor link</a>
  <a href="#" class="anchor">some anchor link</a>
  <p>some paragraph content</p>
</div>

CodePudding user response:

You can loop over a ".content" class and find all anchor and wrap it. something like below.

$(document).ready(function(){
$(".content").each(function() {
  let current=$(this);
  current.find(".anchor").wrapAll("<p class='new'></p>");
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
    <a href="#" class="anchor">some anchor link</a>
    <a href="#" class="anchor">some anchor link</a>
    <p>some paragraph content</p>
</div>
<div class="content">
    <a href="#" class="anchor">some anchor link</a>
    <a href="#" class="anchor">some anchor link</a>
    <p>some paragraph content</p>
</div>

  • Related