Operation of attributes

HTML elements include tag names and several key-value pairs, which are called "attributes".

<a id="test" href="http://www.example.com"> link </a>

In the above code, the a element includes two attributes: the id attribute and the href attribute.

The attribute itself is an object (the Attr object), but in fact, this object is rarely used. Generally, the attributes are manipulated through the element node object (HTMlElement object). This chapter describes how to manipulate these attributes.

Element.attributes attributes

The element object has an attribute of attributes, which returns a dynamic object similar to an array. The members are all attribute node objects of the element label, and real-time changes of attributes will be reflected on this node object. Other types of node objects, although they also have attributes attributes, all return null, so this attribute can be regarded as unique to the element object.

A single attribute can be referenced by serial number or attribute name.

// HTML code is as follows
// <body bgcolor="yellow" onload="">
document.body.attributes[0];
document.body.attributes.bgcolor;
document.body.attributes["ONLOAD"];

Note that the three methods of the above code all return attribute node objects, not attribute values.

The property node object has name and value properties, which correspond to the property name and property value, which are equivalent to the nodeName property and the nodeValue property.

// HTML code is
// <div id="mydiv">
var n = document.getElementById("mydiv");

n.attributes[0].name; // "id"
n.attributes[0].nodeName; // "id"

n.attributes[0].value; // "mydiv"
n.attributes[0].nodeValue; // "mydiv"

The following code can traverse all the attributes of an element node.

var para = document.getElementsByTagName("p")[0];
var result = document.getElementById("result");

if (para.hasAttributes()) {
  var attrs = para.attributes;
  var output = "";
  for (var i = attrs.length - 1; i >= 0; i--) {
    output += attrs[i].name + "->" + attrs[i].value;
  }
  result.textContent = output;
} else {
  result.textContent = "No attributes to show";
}

Standard attributes of elements

The standard attributes of HTML elements (that is, the attributes defined in the standard) will automatically become the attributes of the element node object.

var a = document.getElementById("test");
a.id; // "test"
a.href; // "http://www.example.com/"

In the above code, the attributes id and href of the a element tag automatically become the attributes of the node object.

These attributes are all writable.

var img = document.getElementById("myImage");
img.src = "http://www.example.com/image.jpg";

The above wording will immediately replace the src attribute of the img object, and another picture will be displayed.

This method of modifying attributes is often used to add form attributes.

var f = document.forms[0];
f.action = "submit.php";
f.method = "POST";

The above code adds the submission URL and submission method to the form.

Note that although this usage can read and write attributes, it cannot delete attributes. The delete operator will not take effect here.

The attribute names of HTML elements are case-insensitive, but the attribute names of JavaScript objects are case-sensitive. The conversion rule is that when converting to JavaScript property names, lowercase is always used. If the attribute name includes multiple words, the camel spelling is used, that is, starting from the second word, the first letter of each word is capitalized, such as onClick.

Some HTML attribute names are reserved words of JavaScript and must be renamed when converted to JavaScript attributes. Mainly the following two.

-for attribute changed to htmlFor -class attribute changed to className

In addition, HTML attribute values ​​are generally strings, but JavaScript attributes are automatically converted into types. For example, the string true is converted to a boolean value, the value of onClick is converted to a function, and the value of the style property is converted to a CSSStyleDeclaration object. Therefore, various types of values ​​can be assigned to these attributes.

Standard method of attribute manipulation

Overview

The element node provides six methods to manipulate attributes.

-getAttribute() -getAttributeNames() -setAttribute() -hasAttribute() -hasAttributes() -removeAttribute()

There are a few points to note.

(1) Applicability

These six methods are applicable to all attributes (including user-defined attributes).

(2) Return value

getAttribute() only returns a string, and does not return other types of values.

(3) Property name

These methods only accept the standard name of the attribute and do not need to rewrite the reserved words. For example, for and class can be used directly. In addition, these methods are case-insensitive to attribute names.

var image = document.images[0];
image.setAttribute("class", "myImage");

In the above code, the setAttribute method directly uses class as the attribute name, instead of writing it as className.

Element.getAttribute()

The Element.getAttribute method returns the specified attribute of the current element node. If the specified attribute does not exist, null is returned.

// HTML code is
// <div id="div1" align="left">
var div = document.getElementById("div1");
div.getAttribute("align"); // "left"

Element.getAttributeNames()

Element.getAttributeNames() returns an array, the members are the names of all the attributes of the current element. If the current element does not have any attributes, an empty array is returned. Using the Element.attributes property, you can also get the same result, the only difference is that it returns an array-like object.

var mydiv = document.getElementById("mydiv");

mydiv.getAttributeNames().forEach(function (key) {
  var value = mydiv.getAttribute(key);
  console.log(key, value);
});

The above code is used to traverse all the attributes of a node.

Element.setAttribute()

The Element.setAttribute method is used to add attributes to the current element node. If the attribute with the same name already exists, it is equivalent to editing the existing attribute. This method has no return value.

// HTML code is
// <button>Hello World</button>
var b = document.querySelector("button");
b.setAttribute("name", "myButton");
b.setAttribute("disabled", true);

In the above code, the name attribute of the button element is set to myButton, and the disabled attribute is set to true.

There are two things to note here. First, the attribute value is always a string, and other types of values ​​will be automatically converted into a string. For example, the boolean value true will become the string true; secondly, the in the previous example The disableattribute is a boolean attribute. For the