Appearance
Modifying DOM Structure
Using browser APIs to modify the DOM can be complex and requires handling different browser behaviors. jQuery simplifies this process, allowing you to focus on jQuery objects while it manages the underlying DOM operations.
Adding DOM Elements
To add new DOM nodes, you can use the append()
method. For example, given the following HTML structure:
html
<div id="test-div">
<ul>
<li><span>JavaScript</span></li>
<li><span>Python</span></li>
<li><span>Swift</span></li>
</ul>
</div>
First, select the <ul>
node:
javascript
let ul = $('#test-div>ul');
Then, use append()
to add a new language:
javascript
ul.append('<li><span>Haskell</span></li>');
You can also add DOM objects, jQuery objects, or function objects:
javascript
// Create a DOM object:
let ps = document.createElement('li');
ps.innerHTML = '<span>Pascal</span>';
// Add the DOM object:
ul.append(ps);
// Add a jQuery object:
ul.append($('#scheme'));
// Add a function object:
ul.append(function (index, html) {
return '<li><span>Language - ' + index + '</span></li>';
});
The prepend()
method can be used to add elements to the beginning instead. If the nodes you're adding already exist, jQuery removes them from their original position before adding them to the new location.
To insert a new node between existing ones, use after()
:
javascript
let js = $('#test-div>ul>li:first-child');
js.after('<li><span>Lua</span></li>');
Removing Nodes
To delete DOM nodes, use the remove()
method directly on the jQuery object. This can remove multiple nodes at once:
javascript
let li = $('#test-div>ul>li');
li.remove(); // All <li> elements will be removed
Practice: Adding and Sorting Languages
Add Pascal, Lua, and Ruby to the list and sort the nodes alphabetically:
javascript
let ul = $('#test-div>ul');
// Adding new languages
ul.append('<li><span>Pascal</span></li>');
ul.append('<li><span>Lua</span></li>');
ul.append('<li><span>Ruby</span></li>');
// Sorting the list
let items = ul.children('li').get();
items.sort(function(a, b) {
return $(a).text().localeCompare($(b).text());
});
// Clear the list and append sorted items
ul.empty().append(items);
Testing
You can test the result with the following code:
javascript
(function () {
let s = $('#test-div>ul>li').map(function () {
return $(this).text();
}).get().join(',');
if (s === 'JavaScript,Lua,Pascal,Python,Ruby,Swift') {
console.log('test passed!');
} else {
console.log('test failed: ' + s);
}
})();