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

How to add custom attributes to elements in javascript

coldplay.xixi
Release: 2023-01-04 09:35:24
Original
10931 people have browsed it

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')
Copy after login

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"); //与第一个等价
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template