Please have 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 is:
Hello
World
Expected Result as HTML is:
<div>
<span>Hello</span>
<br/>
<span>World</span>
</div>
What is the error? According to the jQuery Docs (http://api.jquery.com/after/) it should be possible:
.after()
will also work on disconnected DOM nodes.
and
That set can be further manipulated, even before it is inserted in the document.
UPDATE
It seems, that I need to append the first span to the DOM first, before using .after()
. But what is the alternative? If I can't access the DOM, e.g. because I'm in a DOM-unaware part of the code? http://jsfiddle.net/s6VdW/10/
UPDATE 2
I can create a "temporary" div, to which I append the elements to. Then I return the children of that div. Demo: http://jsfiddle.net/s6VdW/13/ - Does that look like the way to go?
span1.after(br).after(span2).length
returns1
, but it should be3
. Maybe you should open a ticket in jQuery's bug tracker. – Raillery