setAttribute () method and getAttribute () method

A, setAttribute () method

setAttribute () method of adding a set of elements or a specified property, and assign it the value specified. (Mainly for custom attributes)

If this attribute exists, or simply modify the property value set.

Browser Compatibility: compatible with all major browsers

grammar:

element.setAttribute(attributename,attributevalue)

parameter:

attributename attribute name added:. essential

AttributeValue : property value add. essential

Return value : No return value

note:

1, HTML element in the HTML document calling setAttribute () when the method, which will have properties (attribute name) parameter lowercase.

2, if the specified attribute already exists, or to modify the transmission property values. If not, it creates the specified property. (This method can only be called by an element node)

3, the property does not exist, the getAttribute () returns null. Or you should use removeAttribute () instead of setAttribute ( 'attribute name', null) to delete the property.

Example:

setAttribute set the attribute on the li element.

     HTML     

< Li > single song </ li > 
< li > anchor stations </ li > 
< li > Ranking </ li >

    JavaScript    

var lis = tab_list.querySelectorAll('li');
for(var i=0;i < lis.length;i++){
         lis[i].setAttribute('index',i);
}

 

Two, getAttribute () method

getAttribute () method returns a specified attribute value of the element.

If the attribute values ​​specified does not exist, it returns null or "" (the empty string).

Browser Compatibility: All major browsers support getAttribute () method.

grammar:

element.getAttribute(attributename)

parameter:

attributeName : need to get the property name property value. essential

return value:

Return Value (string type) specified attribute

note:

1, when this method is called HTML elements in a document in HTML, getAttribute () method will be converted to lowercase first parameter.

2, when the above attribute is specified in the element is not present, all browsers will return null.

3, this method is called when the HTML document is marked as an HTML element, getAttribute() it will first convert its argument to lowercase.

4, so if a property may not exist on the specified element before calling getAttribute (), you should use element.hasAttribute () to detect the presence or absence of this attribute.

Example:

     JavaScript     

function myFunction()
{
var a=document.getElementsByTagName("a")[0];
document.getElementById("demo").innerHTML=a.getAttribute("target");
}

 


Other operating more custom attributes : https://www.cnblogs.com/nyw1983/p/11817145.html

 

 

Guess you like

Origin www.cnblogs.com/nyw1983/p/12005961.html