3

I have several HTML code combinations like this:

<h2></h2>
<p></p>
<iframe></iframe>
<hr/>

and from that I want to create such a code with jQuery:

<div id="sample">
<h2></h2>
<p></p>
<iframe></iframe>
</div>
<hr/>

I could just perform these functions:

$('h2').before('<div id="sample">');
$('iframe').after('</div>')

but these functions doesn't insert only given text, it creats new div sections. I need to put particular parts of HTML into one div section with a help of jQuery because my page contains many of these combinations.

1

2 Answers 2

4

​You can use nextUntil to select sibling elements up to one matching a selector, and wrapAll to wrap the entire matched set in another element. You need to use andSelf to add the original h2 element back into the matched set:

​$("h2").nextUntil("hr").andSelf().wrapAll("<div id='sample'>");​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Sign up to request clarification or add additional context in comments.

3 Comments

for some reason it doesn't work - div sections with id=sample aren't created
but if I perform function $("h2").nextUntil("hr").andSelf().css() it works, what is wrong with that wrapAll
finally I got everything working, Error Console was showing that at the end of this jQuery code exists illegal character, which I guess was copy-paste fault. Also I don't need wrapAll() but simply wrap() function to create seperated div sections. As more than one similar div sections are needed, id can't be used, so in place of id should be class
0
$('h2').nextUntil('hr').andSelf().wrap('<div class="sample">');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.