Javascript method to add custom attributes to elements: 1. Add custom attributes to elements, the code is [obj.setAttribute('attr_name','attr_value')]; 2. Add class attributes to elements.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
How to add custom attributes to elements in javascript:
Add custom attributes to elements
obj.setAttribute('attr_name','attr_value'); //例如obj.setAttribute('class','snow-container')
Three ways to add class attributes to elements
document.getElementsByTagName('body')[0].className = 'snow-container'; //设置为新的 document.getElementsByTagName('body')[0].className += 'snow-container'; //在原来的后面加这个 document.getElementsByTagName('body')[0].classList.add("snow-container"); //与第一个等价
Related free learning recommendations: javascript video tutorial
The above is the detailed content of How to add custom attributes to elements in javascript. For more information, please follow other related articles on the PHP Chinese website!