GetAttribute and SetAttribute Usage

Source: Internet
Author: User

GetAttribute and setattribute can only be used for element nodes.

1. When an element node is obtained with getElementById

/*---------------------------index.html---------------------------*/

<! DOCTYPE html>
<meta name= "Author" content= "Hehe" >
<title>shopping list</title>
<body>
<p id= "purchases" title= "one" >what to buy</p>
<script type= "Text/javascript" src= "Script.js" ></script>
</body>

/*------------------------script.js---------------------------*/

var Paras=document.getelementbyid ("Purchases");
Alert (Paras.getattribute ("title"));
Paras.setattribute ("title", "ABCD");
Alert (Paras.getattribute ("title"));

At this point the warning box shows one, one shows ABCD.

2. When an element node is obtained with getElementsByTagName

/*---------------------index.html-----------------------------*/

<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<meta name= "Author" content= "Hehe" >
<title>shopping list</title>
<body>
<p id= "purchases" title= "one" >what to buy</p>
<p title= "Both" >what to buy</p>
<script type= "Text/javascript" src= "Script.js" ></script>
</body>

/*----------------------------script.js--------------------*/

var paras=document.getelementsbytagname ("P");
for (Var i=0;i<paras.length;i++) {
Paras[i].setattribute ("title", "ABCD");
Alert (Paras[i].getattribute ("title"));
}

Now there are two warning boxes showing ABCD.

Note : getElementById Returns a node, and getElementsByTagName returns an array.

Double quotes are required for getattribute ("") and SetAttribute ("", "").

Alert () is not a display string without the need for double quotes.

GetAttribute and SetAttribute Usage

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.