I. Summary
This article explains how to use jquery to get and manipulate the attributes and CSS styles of elements. The distinction between DOM attributes and element attributes is worth learning.
Two. Foreword
Through the previous chapters we have been able to fully control the jquery wrapper set, either by selecting objects from the selector, or by removing them from the wrapper set, filtering the elements. This chapter explains how to use jquery to get and modify element attributes and styles.
Three. Distinguishing between DOM attributes and element attributes
An IMG tag:
Usually developers are accustomed to the ID, SRC, alt, and so called "attributes" of this element. I call it "element attributes." However, when parsing into a DOM object, the actual browser eventually resolves the label elements into "Dom objects" and stores the element attributes of the elements as "Dom properties". There is a difference between the two.
Although we set the element src is the relative path: images/image.1.jpg
However, it is converted to an absolute path in the DOM properties: http://localhost/images/image.1.jpg.
Even some of the "element attributes" and "Dom properties" have different names, such as the element attribute class above, which corresponds to the classname when converted to DOM attributes.
Keep in mind that in JavaScript we can get or set the DOM properties directly:
<script type="text/javascript">
$(function() {
var img1 = document.getElementById("hibiscus");
alert(img1.alt);
img1.alt = "Change the alt element attribute";
alert(img1.alt);
})
</script>
So if you want to set the CSS style class for the element, you want to use the DOM property className instead of the element attribute class:
img1.className = "classB";
Four. Manipulate DOM Properties
There is no wrapper in jquery for the function "Dom properties", because it is easy to get and set DOM properties using JavaScript. In jquery, the each () function is used to traverse the jquery wrapper set, where the this pointer is a DOM object, so we can apply this in conjunction with native JavaScript to manipulate the element's DOM properties:
$("img").each(function(index) {
alert("index:" + index + ", id:" + this.id + ", alt:" + this.alt);
this.alt = "changed";
alert("index:" + index + ", id:" + this.id + ", alt:" + this.alt);
});
The following is a description of each function:
Each (callback) Returns:jquery wrapper set
Executes the callback method for each element in the wrapper set. Where the callback method takes a parameter that represents the index value of the current traversal, starting at 0.