How to Get and set attributes in js

Source: Internet
Author: User

Copy codeThe Code is as follows:
Function square (num ){
Var total = num * num; // local variable
Return total;
}
Var total = 50; // global variable
Var number = square (20 );
Alert (total); // The result is 50.

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.

This subtle difference will affect the program results.
Copy codeThe Code is as follows:
Body {
Color: white;
Background-color: black;
}

These colors apply not only to the content directly contained in the <body> tag, but also to all elements nested in the body element.

The id attribute is like a hook. It is connected to an element in the document and a style in the CSS style table.

Document. getElementById ("purchases") this call will return an object, which corresponds to a unique element in the document Object, that element
The id attribute value of is purchases.

In fact, each element in the document is an object. Use the methods provided by DOM to obtain any object.

GetElementsByTagName returns an array even if there is only one element in the document.

Example:
Copy codeThe Code is as follows:
Var items = document. getElementsByTagName ("li ");
For (var I = 0; I <items. length; I ++ ){
Alert (typeof items [I]);
}

The display information is all objects.

GetElementByClassName
Returns an array of elements with the same class name.

Get and set attributes
GetAttribute
Object. getAttribute (attribute)
Note: The getAttribute method is not a document object and can only be called through an Element Node object.

SetAttribute
Object. setAttribute (attribute, value)

Example:
Var shopping = document. getElementById ("purchases ");
Shopping. setAttribute ("title", "a list of goods ");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.