I want to add two HTML elements to a Dom element one after another. But this call does not work with jQuery
$("<button>click me</button>").after("<span> or be happy </span>")
.appendTo("#someId");
The reason I cannot combine the two elements in one string is that I want to add a event handler to the first. So what I really want to do is:
$("<button>click me</button>").after("<span> or be happy </span>")
.on("click", function() {
// do something
});
Right now, my workaround is to assign an id to the button and add the “span” in a separate jQuery call. Like so…
$('<button id="uid">click me</button>').on("click", function() {
// do something
});
$('#uid').after('<span> or be happy</span>');
It there a better way?
You should be doing it something like this then:
EDIT
According to the documentation, you can actually insert DOM nodes (and manipulate) even if the nodes are not yet disconnected. This assumes jQuery 1.4+ though.
So if you fit that bill, you should be able to do all that in one statement: