Tuesday, 4 December 2012

jQuery: get and set information for DOM elements


jQuery is a great tool when we need to manipulate elements in our web page.
Today I would like to focus your attention on some useful methods that allow us to get or set information of DOM elements.
We are talking about:
1) .text()
2) .html()
3) .val()
4) .attr()

Let's see them one by one.
The method allow us to get or set the text of an element.
Considering a div like:
<div id="test">This is an example</div>
we can get the text contained using:

The same method allows us to set a text inside a container. If the container is not empty, the text inside will be replaced. We can use the method in the following way:
$("#test").text("Replaced text inside the container")
The .html() method works in a similar way. it gets or sets the html content of an element (including the code).
If our container is:
<div id="test"><b>This is a bold text</b></div>
the method:
will get:
<b>This is a bold text</b>
As you may see the <b> tags are included in what we get.
If we want to set html code to an element, using something like:
$("#test").html("<i>This is italics</i>")
The result will reflect the tags, changing the content of our div from
This is a bold text
This is italics

This method allow us to get or set the value of a form field. it works as the other two methods above.
Let's imagine a form containing an input element like
<input type="text" id="test" value="Hello!">
The method used as:
will get the value of the input box ("Hello!").
If we want to set the value, we can use the method the following way:
This method is indeed very powerful as you may imagine.

The last method is used to get or set attribute values.
If we have a link like:
<a href="http://thewebthought.blogspot.com" id="test">the web thought</a>
The following code:
will get:
$("#test").attr("href", "http://thewebthought.blogspot.com/p/search.html")
will set or change the attribute to the above URL.

Wow! Just one long sentence to describe all - I'm really impressed!

Ok, leaving self-indulgence apart... what do you think about the above methods? Aren't they interesting?
please leave your ideas in the comments section below!

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.