jQuery's strength is the ease with which you can select and manipulate elements on the page. You have used a selector method already to select all <div> elements that have an ID of div1:
$("#div1").html("hello jQuery");
jQuery supports many different ways to select an element or elements that should meet all but the most awkward requirements. Table 12-1 lists examples of other selection methods you might want to use.
In addition to the previous standard selectors, more modern selectors are also available (browser support may differ, but you are probably safe with IE 7+ and Firefox 3+); see Table 12-2.
jQuery also provides some built-in selectors; see Table 12-3.
Selector | Effect |
---|---|
$(":button")[0].innerText="hello jquery2"; | Changes the innerText property of first button element |
$(":contains(alex)") | Selects all elements containing the text alex |
$(":hidden") | Selects all hidden elements |
$(":selected") | Selects all selected elements |
$(":visible") | Selects all visible elements |
$("div:not(.standardDiv)") | Selects all <div> elements that do not have a class of standardDiv |
So, you have used one of the preceding selector methods and now have a collection of matching elements (a wrapped set). How can you work with them? jQuery has a number of different methods to work with collections; see Table 12-4.
The .each() method works like the foreach statement in C# or Visual Basic and allows you to iterate through a set of elements. The following example iterates through a set of <div>s, modifying the innerHTML property on each element:
function showDivNumber() { $("div").each(function(index) { this.innerHTML = "I am div number " + index; }); }
Of course, if you just wanted to set the same text to each <div> element, you could apply the change to the wrapped set as follows:
$("div").html("I am a div");
jQuery provides methods to read, set, and remove attributes on page elements; see Table 12-5.
Example | Meaning |
---|---|
alert($("#div1").attr("id")); | Retrieves the id attribute from <div> |
$("#div1").attr("title", "hello"); | Sets the title attribute to "hello" |
$("#div1").removeAttr("title") | Removes the title attribute |
$("#div1").addClass("specialDiv"); | Adds the specialDiv CSS class to element |
3.138.122.210