Garry Garry - 3 months ago 11
HTML Question

JQuery add opening of a div to element, then close div after different element

I have looked through jquery documentation and every example I've tried causes issues for me. I have a bunch of list items with different classes, I'd simply like to add a div () before one particular li item.

Then I'd like to target a different list item and add a closing div ().

When I have tried this using prependTo and append etc but none of them are working as they automatically close the div I have opened. My code so far looks like this:

<ul>
<li class="textbox email">This is the email list item</li>
<li class="textbox address">This is the address list item</li>
<li class="textbox aboutme">This is the aboutme list item</li>
</ul>


and I would like it to come out as:

<ul>
<li class="textbox email">This is the email list item</li>
<div class="open"> <!-- div id opened here -->
<li class="textbox address">This is the address list item</li>
<li class="textbox aboutme">This is the aboutme list item</li>
</div> <!-- div is closed here -->
</ul>


Currently, if I try:

$("<div>").prependTo(".email");//prependTo append at inside top


The output will automatically close the div as such:

<ul>
<div></div> <!-- div closed automatically instead of remaining open -->
<li class="textbox email">This is the email list item</li>
<li class="textbox address">This is the address list item</li>
<li class="textbox aboutme">This is the aboutme list item</li>
</ul>

Answer

Edit: this answer is old, and the fiddle is broken. Please use Gautum's answer below (http://stackoverflow.com/a/26014879/1139444)


As it has already been stated this is not a good idea but here is a demo on how you could do i with jQuery.

jsFiddle

As you can see from the code it inserts the div and then adds the li to the created div. All you need now is to add another line to addClass so that the div has the class of open.

Comments