DOM manipulation
Previously, you've seen that JavaScript frameworks make it easy to get specific elements using selectors and DOM traversal. However, in order to change the content and appearance of specific elements on a web page, you need to manipulate the DOM and apply the changes. Using pure JavaScript would be a lot of work, but luckily most JavaScript frameworks provide useful functions that make doing this easy.
Suppose you have a box with the ID the-box.
<div id="the-box">Message goes here</div>
Use jQuery to change its text to "Message goes here", which can be easily used like this:
$('#the-box').html('This is the new message!');
In fact, you can use HTML code in functions and it will be parsed by the browser, for example:
$('#the-box').html('This is the <strong>new</strong> message!');
In this example, the content inside the DIV element looks like this:
<div id="the-box">This is the <strong>new</strong> message!'</div>
Of course, in the example you need to use special characters such as greater than or less than, rather than specifying special HTML entity codes. You can use jQuery's text function instead:
$('#the-box').text('300 >200');
The code after updating the div element is as follows:
<div id="the-box">300 > 200</div>
In the example above, existing content is replaced with new content. What if you just want to append some information to the text? Fortunately, jQuery provides the append function for this purpose.
$('#the-box').append(', here goes message');
After performing the above operations on the original div, the content in the div element looks like this:
<div id="the-box">Message goes here, here goes message</div>
Instead of appending, you can prepend content, inserting it before existing content instead of after it. Additionally, jQuery provides functions to insert content within a given element, either before or after. There are also functions to replace content, clear content, remove elements, clone elements, and more.
In addition to DOM manipulation functions, JavaScript frameworks usually contain several functions to manipulate styles and classes of elements. For example, you have a table that highlights a row when the mouse passes over it. You can create a special class named hover that you can dynamically add to a row. Using YUI, you can use the following code to determine whether the row has a hover class name. If it does, it will be ignored. If not, it will be added.
if(row.hasClass('hover')) row.removeClass('hover'); else row.addClass('hover');
Likewise, most JavaScript frameworks have built-in functions for manipulating CSS.