This section of html takes the following as an example
1. Get and set element properties through the attributes of HTMLElement type (object)
var div = document.getElementById("myDiv");
var img = document.getElementById("img1");
var a = document.getElementById("myA");
//Get element properties
alert(div.id); //"myDiv"
alert(div.className); //"bd", this is not div.class, because class is a reserved keyword
alert(div.title); //"I am div"
alert( a.href); //http://www.baidu.com
//Set element properties
div.id = "myDiv2"; //Change id to "myDiv2"
div.className = "ft"; //class is changed to "ft". If there is a style named "ft", it will immediately change to the "ft" style, and the browser will respond immediately
div.title = "I am myDiv2" ; //Change title to "I am myDiv2"
div.align = "center"; //Set center alignment
img.src ="images/img1.gif"; //Set image path
a.innerHTML = "Sina"; //"Baidu" is changed to "Sina"
a.href = "http://www.sina.com.cn"; //Reset the hyperlink
2. Get, set, and remove the attributes of elements through the getAttribute(), setAttribute(), and removeAttribute() methods (not recommended, the first two methods have exceptions in IE6 and 7, and the third method IE6 Not supported, can be used when setting custom attributes)
getAttribute() method is used to obtain element attributes. It accepts one parameter, which is to get the attribute name of the element. The
setAttribute() method is used to set the attribute of the element. It accepts two parameters, namely to obtain the attribute name and attribute value of the element. The
removeAttribute() method is used to remove the attribute of the element. Accepts one parameter, which is the attribute name of the element to be removed
var div = document.getElementById("myDiv");
var img = document.getElementById("img1");
var a = document.getElementById("myA");
//Get element properties
alert(div.getAttribute("id")); //"myDiv"
alert(div.getAttribute("class")); //"bd", note that this is class, not className, Different from the above
alert(div.getAttribute("title")); //"I am div"
alert(a.getAttribute("href")); //http://www.baidu. com
//Set element attributes
div.setAttribute("id","myDiv2"); //Change id to "myDiv2"
div.setAttribute("class","ft"); / /class is changed to "ft", here it is also class, not className
div.setAttribute("title","I am myDiv2"); //title is changed to "I am myDiv2"
div.setAttribute ("align","center"); //Set center alignment
img.setAttribute("src","images/img1.gif"); //Set image path
//Remove element attributes
div.removeAttribute("class"); //Remove the class attribute
3. Get, set, and remove the attributes of the element through the attributes attribute
var div = document.getElementById("myDiv");
//Get element properties
alert(div.attributes["id"].nodeValue); //"myDiv"
//Set element attributes
div.attributes["id"].nodeValue = "myDiv2"; //id Change to "myDiv2"
//Remove element attributes
div.attributes.removeNamedItem("class"); //Remove class attributes