Previously, we looked at how you might work with the DOM by using some of the various methods that jQuery provides to you to modify the DOM. Let’s look at a simple example where we will add content to the DOM, and then manipulate it further.
So we’ll start off with something simple, our HTML page.
<p>I'm outside of the danger zone... but still a paragraph.</p>
<div id="data">
<p>I was here first.</p>
</div>
Then we’re going to change the DOM using the methods we get access to through jQuery. First, replacing the paragraph that was there, and adding some new content using the append()
and prepend()
methods. This makes sure the data is put where we want it.
// remove the paragraph inside of the div#data
$('#data p').remove();
// add a new DOM element within our selected tag
$('#data').append("<p>This is some important information.");
// as a prepend this is moved to the front of the selected element
$('#data').prepend("<h1>Important Info</h1>");
// add a last DOM element
$('#data').append("<p>One more paragraph...</p>");
However, this only adds data, and the associated tags, and there is so much more you can do, like manipulate the styles.
// Apply styles
$("h1").css("color", "blue");
$("p").css({
"font-size": "18px",
"color": "gray"
});
If you run this example, you notice that all the paragraph tags get the same style. If you only want the new tags to get it, you must update the selector to be $('#data p')
. This will limit it to just the paragraph tags within the area we are working in.
Notice that with the css
() you can pass in two parameters, a rule, and a value, or a JavaScript object of multiple values, to simplify the process. Neither of these methods actually creates a class, which can be done in your source HTML, and then add the class with the addClass()
method, like we saw earlier.
jQuery Working with the DOM was originally found on Access 2 Learn
2 Comments
Comments are closed.