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:
Let's see them one by one.
The method allow us to get or set the text of an element.
Considering a div like:
we can get the text contained using:
<div id="test">This is an example</div>
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>
As you may see the <b> tags are included in what we get.
<b>This is a bold text</b>
If we want to set html code to an element, using something like:
The result will reflect the tags, changing the content of our div from
$("#test").html("<i>This is italics</i>")
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
The method used as:
<input type="text" id="test" value="Hello!">
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:
The following code:
<a href="http://thewebthought.blogspot.com" id="test">the web thought</a>
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!