简体   繁体   中英

Why is .getAttribute returning null for data-* attribute

I have some HTML and I'm trying to get the value of "data-nChargers" with this script

 var noOfChargers = document.getElementById("chargers-list") .getAttribute("nChargers"); console.log(noOfChargers); 
 <div id="chargers-list" data-nChargers="4"></div> 

but it returns null. What am I doing wrong?

The attribute is data-nChargers which can be accessed through dataset or getAttribute("data-nChargers")

 var e = document.getElementById("chargers-list"); console.log(e.getAttribute("data-nChargers")); console.log(e.dataset.nchargers); 
 <div id="chargers-list" data-nChargers="4"></div> 

Try

getAttribute("data-nChargers"); instead.

This happens because getAttribute method looks for that exact name. If you want to get data attributes you should use .dataset.nChargers instead.

More information in : https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

Best regards.

You need to change getAttribute("nChargers"); to getAttribute("data-nChargers");

 var noOfChargers = document.getElementById("chargers-list"). getAttribute("data-nchargers") console.log(noOfChargers); 
 <div id="chargers-list" data-nChargers="4"></div> 

The full attribute name is data-nChargers , not simply nChargers .

document.getElementById("chargers-list").getAttribute('data-nChargers')

If you want to use only nChargers , you could use the dataset property:

document.getElementById("chargers-list").dataset.nChargers

dataset ignores the data- prefix and converts dashed words (ie n-chargers ) to camel-case (ie nChargers ).

https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

The modern way is using dataset . Note the attribute name is lowercased and then hyphens are removed and converted to camel case.

 console.log(document.getElementById("chargers-list").dataset.nchargers); 
 <div id="chargers-list" data-nChargers="4"></div> 

The getAttribute() function requires you to use the whole name of the attribute. In this case data-nchargers .

Another option is to use the dataset property. In this case it would not require the data- prefix.

var list = document.getElementById("chargers-list");
var noOfChargers = list.dataset.nchargers;
console.log(noOfChargers);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM