JQuery.after () is not working properly
Please take a look at: http://jsfiddle.net/s6VdW/
HTML:
<div id="test"></div>
JS:
var span1 = $("<span/>").text("Hello");
var br = $("<br/>");
var span2 = $("<span/>").text("World!");
span1.after(br).after(span2);
$("#test").append(span1);
Expected Result:
Hello
World
HTML expected result:
<div>
<span>Hello</span>
<br/>
<span>World</span>
</div>
What mistake? According to jQuery docs ( http://api.jquery.com/after/ ) this should be possible:
.after()will also work with detached DOM nodes.
and
This set can be further processed, even before it is inserted into the document.
UPDATE
It seems I need to add the first range to the DOM first before using it .after(). But what is the alternative? If I can not access the DOM, for example. because I in the DOM do not know part of the code? http://jsfiddle.net/s6VdW/10/
UPDATE 2
"" div, . . : http://jsfiddle.net/s6VdW/13/ - ?
after, - :
// Initialize jQuery objects
var span1 = $("<span/>").text("Hello");
var br = $("<br/>");
var span2 = $("<span/>").text("World!");
// First step : Add the first element to your div
$("div").append(span1);
// Second step : Add the differents elements with the add method (note that I inversed the order to work fine because the after is applied to span1 and not to the last added element.
span1.after(span2).after(br);