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?
Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.
You can use this jquery data() syntax for get data-id attribute value. $("selector"). data("textval"); You can use this jquery data() syntax for get data-textval attribute value.
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With