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 >
<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 >');
}
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 />');
});
CodePudding user response:
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 >
<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 >Lorem ipsum</p>
<p >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>
CodePudding user response:
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 />');
});