Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.after() does not work as expected

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?

like image 281
Sandro Avatar asked Oct 22 '22 15:10

Sandro


1 Answers

The problem is you create span1 dynamically at the same time you use .after() before creating that span element. span1.after(br).after(span2); in this line it is gonna search for span1 element to apply .after() but that element is not there. If you understand clearly about why do we have to use .ready() it has similarity here. Your code should be like this

var span1 = $("<span/>").text("Hello");
var br = $("<br/>");
var span2 = $("<span/>").text("World!");

$("#test").append(span1);
span1.after(span2).after(br);

And remember .after() add elements from left to right so you have to use .after() in the order of 9 to 1 so it will give result 1 to 9.

Hope you got the answer. :)

like image 128
Faizul Hasan Avatar answered Oct 24 '22 11:10

Faizul Hasan