Home > Article > Web Front-end > js method of getting and setting attributes_javascript skills
function square(num){
total = num*num;//global variable
return total;
}
var total = 50;//global variable
var number = square(20);
alert(total);//The result is 400
The id attribute is like a hook. One end is connected to an element in the document, and the other end is connected to a certain style in the CSS style sheet
document.getElementById("purchases") This call will return an object. This object corresponds to a unique element in the document object. The id attribute value of that element
is purchases
Actually, every element in the document is an object. Any object can be obtained using the methods provided by the DOM.
getElementsByTagName returns an array, even if there is only one element in the entire document, an array is returned.
Example:
getElementByClassName
also returns an array of elements with the same class name
Getting and setting attributes
getAttribute
object.getAttribute(attribute)
Note: The getAttribute method does not belong to the document object, it can only be called through the element node object.
setAttribute
object.setAttribute(attribute,value)
Example:
var shopping = document.getElementById("purchases");
shopping.setAttribute("title","a list of goods");