Reputation: 2082
I got a list that i wan't to interrupt via 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 that was easy by doing: $(".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/
Upvotes: 4
Views: 258
Reputation: 5728
As far as I know .after
needs an argument which is a proper DOM text or object.
$(</ul><h1>Title</h1><ul>)
is started from an end tag so </ul>
is ignored. <ul>
is not finished to jquery added an end tag for <ul>
Upvotes: 1
Reputation: 195992
Jquery works with valid HTML only, not string parts.
So you cannot pass broken html to the after()
method.
You will need to split the ul
your self and add the other elements in between.
$(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/
Upvotes: 4