Creating Elements
Creating elements using HTML tags isn’t the only way to do it — in fact it’s possible to create, modify and insert elements from JavaScript.
Here’s an example that creates a div
, adds some text to it and appends it as the last element in the body:
var div = document.createElement('div');
div.textContent = "Sup, y'all?";
div.setAttribute('class', 'note');
document.body.appendChild(div);
So document.createElement
is used with an HTML tag to create the element. The textContent
is then modified and then the class attribute is modified using setAttribute
. This could also be used to add a data attribute or any other kind of attribute, like you can in HTML! Finally the element is appended to the body using the body
element’s appendChild
method.
It’s essentially equivalent to <div class="note">Sup, y'all?</div>
.
In fact, all elements have the appendChild
method, so having done the above it’s possible to do the following:
var span = document.createElement('span');
span.textContent = "Hello!";
div.appendChild(span);
The span
will be added to the end of the div
element.
Removing an element
Removing elements is just as fun. Each DOM element has a property that’s actually the DOM element’s parent. To remove an element, you call the removeChild
method of the parent, passing the child element you want to remove. Something like this:
div.parentNode.removeChild(div);
Simple, eh?
Creating with jQuery
The other alternative is to use jQuery’s element creation syntax. This example does the same as the above examples combined:
var div = $('<div/>').text("Sup, y'all?").appendTo(document.body);
$('<span/>').text('Hello!').appendTo(div);