Distinguish bet...LOGIN

Distinguish between DOM attributes and element attributes

Distinguish between DOM attributes and element attributes

An img tag:

##<img src="images/image.1.jpg" id="hibiscus" alt=" Hibiscus" class="classA" />
Usually developers are accustomed to calling id, src, alt, etc. the "attributes" of this element. We call this "element attribute". However, when parsing into a DOM object, the actual browser will eventually parse the tag element into a "DOM object" and store the element's "element attributes" as "DOM attributes". There is a difference between the two.

Although we set the src of the element to be a relative path:

images/image.1.jpg
But it will all appear in the "DOM Attributes" Convert to an absolute path:

http://localhost/images/image.1.jpg
Even the names of some "element attributes" and "DOM attributes" are It's different. For example, the element attribute class above is converted into a DOM attribute and corresponds to className.

Keep in mind that in javascript we can directly get or set "DOM attributes":

<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 of an element, you need to use the DOM attribute "className" instead of the element attribute "class:

img1.className = "classB";
There is no wrapper function for operating "DOM properties" in jQuery, because it is very simple to use javascript to get and set "DOM properties". Provided in jQuery The each() function is used to traverse the jQuery package set, where the this pointer is a DOM object, so we can apply this with native javascript to operate the DOM attributes of the element:

   $("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 the each function :

each( callback ) Returns: jQuery wrapper set



Execute the callback method for each element in the wrapper set. The callback method accepts a parameter, indicating the currently traversed Index value, starting from 0.


Next Section

<!DOCTYPE html> <html> <body> <p id="intro">Hello World!</p> <script> x=document.getElementById("intro"); document.write(x.firstChild.nodeValue); </script> </body> </html>
submitReset Code
ChapterCourseware