Two ways to get custom attributes in js

js to get two methods of custom attributes

Four ways to get properties

First get an element: var elem = document.getElementById(‘elem’);

1 1. Point (can not get custom attributes):

2. [] can also get attributes, which is beneficial for parameter transfer operations.

elem.style[‘background’] = ‘yellow’

1

3. getAttribute(): The early method of obtaining custom attributes.

var foo = elem.getAttribute(‘ancheng’);//Ancheng

1

It is also possible to set:

elem.setAttribute(‘ancheng’,’Ancheng’);

1

4. data-* (the way to get custom attributes that is often used now)

console.log(elem.dataset.user);

1

Important: If the name of the * has an underscore, it will be converted to a small hump.

console.log(elem.dataset.userName)

1

Note: You can add custom attributes directly in js, but it can only be used in js, because you haven’t added it to html yet.

elem.myColor = ‘red’;

console.log( elem.myColor );…

The post js two ways to get custom properties first appeared on Lenix Blog .

This article is reprinted from https://blog.p2hp.com/archives/9888
This site is for inclusion only, and the copyright belongs to the original author.