Minor jQuery insertion issue

I have a list that I cannot interrupt with javascript to add a title:

From:

<ul> <li>1</li> <li class="afterthis">2</li> <li>3</li> <li>4</li> </ul> 

To:

 <ul> <li>1</li> <li class="afterthis">2</li> </ul> <h1>Title</h1> <ul> <li>3</li> <li>4</li> </ul> 

I thought it was easy to do: $(".afterthis").after("</ul><h1>Title</h1><ul>");

but it doesn’t close the list, it moves the end tag, it inserts <h1>Title</h1><ul></ul>

to see the problem see this jsfiddle http://jsfiddle.net/Fx74b/14/

+4
source share
2 answers

JQuery only works with valid HTML, not string parts.

Thus, you cannot pass the broken html to the after() method.

You need to split ul your self and add other elements between them.

 $(document).ready(function() { var splitelement = $(".afterthis"); // find the element which will be used for the split var ul = splitelement.parent(); // find the relative ul var newul = $('<ul>'); // create the new ul that will follow the existing one newul.append( splitelement.nextAll() ); // move the rest of the li elements to the new ul ul.after("<h1>Title</h1>").next().after(newul); // insert the title and then then ul }); 

demo http://jsfiddle.net/gaby/ph5UM/

+4
source

As far as I know, .after needs an argument, which is the correct text or DOM object.
$(</ul><h1>Title</h1><ul>) run from the end tag, so </ul> ignored. <ul> not finished so jquery adds end tag for <ul>

+1
source

All Articles