Question

Currently have my page setup as:

<body id="some-id">

   <div class="some-class">
   </div>
   <!-- some-class -->

</body>

I've tried using append and before, however, it's not quite doing what I want to do.

I'm trying to add a div with id inserted-div like this:

<body id="some-id">

<div id="inserted-div">

   <div class="some-class">
   </div>
   <!-- some-class -->

</div>
<!-- inserted div -->

</body>

Each time I use something, for example: $('body').appendto("<div id='inserted-div'>"); it either won't insert or it will insert the </div> after the inserted <div> rather than placing the </div> before the closing body. Tried prepend and prependto but no luck.

Était-ce utile?

La solution

You are looking for wrap method.

$('.some-class').wrap('<div id="inserted-div"></div')

$('body').prepend -- will add a div as the first child of the body.

$('body').append -- will add a div as the last child of the body.

But in your case you want the inserted-div as a wrapper for an already existing div.

Check Fiddle

To target just the first instance you can either use

$('.some-class').first() or $('.some-class:eq(0)')

Autres conseils

If you want to wrap something around the entire body content, try:

$("body > *").wrapAll("<div id='inserted-div'/>");

If you want to wrap around the first DIV in the body:

$("body > div:eq(0)").wrap("<div id='inserted-div'/>");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top