Home  >  Article  >  Web Front-end  >  How to add custom attributes to elements in javascript

How to add custom attributes to elements in javascript

coldplay.xixi
coldplay.xixiOriginal
2021-04-08 17:49:5310822browse

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.

How to add custom attributes to elements in javascript

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn