Creating and Removing Elements

From time to time, we need to create new HTML elements so we can insert them into our document. We can use the jQuery function to create elements. This is especially useful when these new elements need events or other behaviors added.

jqueryprimer/create_elements.html
 
var​ input = $(​"input"​);

Although we could use document.createElement("input"); to accomplish this, we can call additional methods easily if we use the jQuery function.

jqueryprimer/create_elements.html
 
var​ element = $(​"<p>Hello World</p>"​);
 
element.css(​"color"​, ​"#f00"​).insertAfter(​"#header"​);

This is another example where jQuery’s chaining helps us build and manipulate structures quickly.

We also need to remove things from the DOM from ...

Get HTML5 and CSS3, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.