简体   繁体   中英

Access 'data-' attribute without jQuery

Can I access a data- attribute without jQuery?

It's easy with jQuery, but I can't see anywhere how to do it without jQuery.

If I search on Google 'without jQuery' all I get is jQuery examples.

Is it even possible?

On here I found this example:

<div id='strawberry-plant' data-fruit='12'></div>
<script>
    // 'Getting' data-attributes using getAttribute
    var plant = document.getElementById('strawberry-plant');
    var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
    // 'Setting' data-attributes using setAttribute
    plant.setAttribute('data-fruit', '7'); // Pesky birds
</script>

So it would appear very doable.

Update: Since Microsoft is now (2020) phasing out the old Internet Explorer engine in favour of a Chromium based Edge, the dataset property is likely to work everywhere. The exception will, for a time, be organizations and corporate networks where IE is still forced. At the time of writing this though - jsPerf still shows the get/setAttribute method as being faster than using dataset, at least on Chrome 81.

You could use the dataset attribute. As in:

element = document.getElementById("el");
alert(element.dataset.name); // element.dataset.name == data-name

It's just an attribute ... use getAttribute as with any other attribute : https://developer.mozilla.org/en/docs/DOM/element.getAttribute

Or am I missing the point of your question.

You can also use:

getAttribute('data-property');

Which is a bit cleaner and easier to read.

This will get the value of the data attribute.

I think you can try this:

var ele = document.getElementById("myelement");
if (ele.hasOwnProperty("data")) {
  alert(ele.data);
}

OR use

alert(ele['data-property']);

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