0

I'm trying to wrap two words in one div no matter their positions (so basically they're treated as "start" and "end" tags).

<p>Start Tag</p>
<p>Lorem ipsum</p>
<p>Lorem ipsum</p>
<p>Lorem ipsum</p>
<p>Lorem ipsum</p>
<p>End Tag</p>

The end result should be

<div class="wrapper">
 <p>Start Tag</p>
 <p>Lorem ipsum</p>
 <p>Lorem ipsum</p>
 <p>Lorem ipsum</p>
 <p>Lorem ipsum</p>
 <p>End Tag</p>
</div>

I tried

$('p').each(function() {
        if ($(this).text() == 'Start Tag') {
            $(this).before('<div class="wrapper">');
        }
        if ($(this).text() == 'End Tag') {
            $(this).after('</div>');
        }
    });

But for some reason it creates the whole div before the 'Start Tag' and does nothing after. I'm trying to split the " and the close tag "" so that it starts before the Start tag and ends after the End tag.

EDIT: Found the solution as what I needed is that sometimes there are multiple of these:

$('p:contains("Start Tag")').each(function() {
    $(this).nextUntil('p:contains("End Tag:")').wrapAll('<div class="wrapper" />');
});
DNa
  • 67
  • 4
  • 1
    Does this answer your question? [jQuery - use wrap() to wrap multiple elements?](https://stackoverflow.com/questions/3475594/jquery-use-wrap-to-wrap-multiple-elements) – DBS Jul 18 '22 at 10:52

2 Answers2

0

When reading your question, as I understand you asking to wrap your paragraph tags with the parent div class called wrapper. below code is your original code,

<p>Start Tag</p>
<p>Lorem ipsum</p>
<p>Lorem ipsum</p>
<p>Lorem ipsum</p>
<p>Lorem ipsum</p>
<p>End Tag</p

You need as result as below,

**<div class="wrapper">
 <p>Start Tag</p>
 <p>Lorem ipsum</p>
 <p>Lorem ipsum</p>
 <p>Lorem ipsum</p>
 <p>Lorem ipsum</p>
 <p>End Tag</p>
</div>**

In here you can get expected result using the wrapAll() jQuery function. This is the answer,

<script>
  $("p").wrapAll("<div class='wrapper'>");
</script>

here is the sandbox URL to play

Let understand this furthermore. let say your original html as below.

<p>Start Tag</p>
<p>Lorem ipsum</p>
<p class="third">Lorem ipsum</p>
<p class="third">Lorem ipsum</p>
<p>Lorem ipsum</p>
<p>End Tag</p>

And you need to wrap wrapper div with p tags class called third. you have to code as below.

<script>
  $(".third").wrapAll("<div class='wrapper'>");
</script>
0

Found the solution to my problem (as I needed an expansive code that would work on multiple instances)

$('p:contains("Start Tag")').each(function() {
    $(this).nextUntil('p:contains("End Tag")').wrapAll('<div class="wrapper" />');
});
DNa
  • 67
  • 4