DOM attribute node operation

There are two ways to operate attribute nodes. One is to operate attribute nodes in the way of ordinary objects, and the other is to operate attribute nodes in the way of attribute nodes.

1. Element nodes. Attribute or element node [attribute]

If we can treat element nodes like normal objects, by element nodes. Properties or element nodes to set properties.

Note: Only className can be used to set the class

1.1 Obtaining Attributes

var img = document.getElementsByTagName('img') [0];
var box = document.getElementsByClassName("box") [0];
var input = document.getElementsByTagName("input") [0];
// Get the properties node
console.log(img.src);
console.log(box.className); // Note that the class attribute uses className
console.log(input["type"]);
Copy the code

1.2 Setting Properties

var img = document.getElementsByTagName('img') [0];
var box = document.getElementsByClassName("box") [0];
var input = document.getElementsByTagName("input") [0];

// Set the property value
img["src"] = "img/fengche.png";
box.className = "bigBox"; // Note: when setting the class attribute, use className
input.placeholder = "Please enter your password";
input.type = "password";
Copy the code

2. Element nodes. Method ()

2.1 the getAttribute

Element node. GetAttribute (name) Gets the value of the attribute

var img = document.getElementsByTagName('img') [0];
var box = document.getElementsByClassName("box") [0];
var input = document.getElementsByTagName("input") [0];
// Get the attribute value
var src = img.getAttribute("src");
console.log(src);
var className = box.getAttribute("class");
console.log(className);
var type = input.getAttribute("type");
console.log(type);
Copy the code

2.2 the setAttribute

Element node. setAttribute(attribute name, attribute value) Sets or modifies an attribute value.

var img = document.getElementsByTagName('img') [0];
var box = document.getElementsByClassName("box") [0];
var input = document.getElementsByTagName("input") [0];
// Set the property value
img.setAttribute("src"."img/fengche.png");
box.setAttribute("class"."bigBox");
input.setAttribute("type"."password");
Copy the code

2.3 hasAttribute

Element node. HasAttribute determines whether the object contains the attribute.

var img = document.getElementById("img");
if (img.hasAttribute("class")) {
    console.log("Contains the class attribute");
}else {
    console.log("Does not contain the class attribute");
}
2.4RemoveAttribute Element node removeAttribute(attribute name) Deletes an attribute.var img = document.getElementsByTagName('img') [0];
var box = document.getElementsByClassName("box") [0];
var input = document.getElementsByTagName("input") [0];
// Delete attributes
img.removeAttribute("title");
box.removeAttribute("class");
input.removeAttribute("type");
Copy the code