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. :)