JQuery: interacting with the wrapped set – part VIII
In the previous post, we’ve met several basic operations that affect the DOM of the current page. However, there will be times when we’re interested in getting the contents of one or more elements. When that happens, we’re probably interested in getting the text or in getting the inner HTML of those items. JQuery helps in these cases too by introducing two methods: text and html.
The html method can be used for getting the inner HTML of a DOM element. For instance, the following snippet will show you the inner HTML of the first div of the wrapped set:
$("div").html()
Setting the inner HTML is as easy as passing a string to the html method. As you might expect, doing this affects all the items of the wrapped set:
$("div").html("<p>hi</p>")
The previous snippet replaces the content of all the div elements of the current page.
The text method is similar, but concentrates on getting the text from within the element. Notice that, unlike the html method, using this method returns the text of all elements maintained on the wrapped set. take a look at the following snippet:
$("div").text()
The previous expression concatenates all text nodes placed inside of all of the divs of the current page. For instance, if you had the following HTML:
<div id="body" style="border: solid 1px red">
<p>Today is a beautiful day for more JQuery learning.</p>
<p>I'd say that it's also a good day to hit the beach.</p>
</div>
<div id="b" class="main secondary">something</div>
then the previous snippet would return something like “Today is a beautiful day for more JQuery learning. I'd say that it's also a good day to hit the beach. something.”.
Setting the text through the text method means that you’ll end up replacing the inner HTML of the items of the wrapped set with the text you’re passing. And that’s it for this post. Keep tuned for more on JQuery.