3

Given this markup:

<h1>Lorem ipsum!</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p>
<p>Aliquam erat volutpat.</p>

How can I surround the two existing paragraphs with a new div using JavaScript?

Desired outcome:

<h1>Lorem ipsum!</h1>
<div>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p>
<p>Aliquam erat volutpat.</p>
</div>
KatieK
  • 13,586
  • 17
  • 76
  • 90
  • No, no jQuery, no library at all. – KatieK Jul 26 '10 at 20:47
  • possible duplicate of [Wrapping an Element using Pure JavaScript !!](http://stackoverflow.com/questions/3337587/wrapping-an-element-using-pure-javascript) – KatieK Jul 26 '10 at 22:56

4 Answers4

2

jquery has a wrap method if you are using it (and if not, why not :) )

µBio
  • 10,668
  • 6
  • 38
  • 56
1

See this question for a solution using plain JavaScript.

Community
  • 1
  • 1
Niels van der Rest
  • 31,664
  • 16
  • 80
  • 86
  • +1 - sAc's answer contains a nice solution and it was asked moments ago. We can't possibly be answering the same question for each new type of element :) – Anurag Jul 26 '10 at 19:29
  • Yes, I did have a déjà vu moment when I read this question. But as the other question was specifically about a non-jQuery solution, I didn't want to call this a duplicate :) – Niels van der Rest Jul 26 '10 at 19:56
  • Oh dear, my apologies. I didn't find that other question when I was searching. I've asked some follow-up questions in there. – KatieK Jul 26 '10 at 21:36
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – ProgramFOX Mar 08 '14 at 10:38
  • @ProgramFOX In general I agree with you completely, but in this case it links to another SO question which will probably be around at least as long as this answer. Also I'd like people to upvote the original question and answer ;) – Niels van der Rest Mar 08 '14 at 15:06
0

You should add a class to the paragraph tags and use the wrapAll() function.

$(".yourPclass").wrapAll("<div/>");

(This was making an assumption if you were using jquery*)

jstoneky
  • 1
  • 1
0

https://developer.mozilla.org/en/insertbefore or https://developer.mozilla.org/en/appendchild if you want to manually do it.

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434