Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access 'data-' attribute without jQuery

Tags:

javascript

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?

like image 881
user2143356 Avatar asked Apr 09 '13 20:04

user2143356


People also ask

How do I query select a data attribute?

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.

How get value from data attribute in jQuery?

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.

How do I find data attributes?

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.


2 Answers

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.

like image 111
fredrik Avatar answered Sep 21 '22 17:09

fredrik


You could use the dataset attribute. As in:

element = document.getElementById("el"); alert(element.dataset.name); // element.dataset.name == data-name 
like image 38
tomor Avatar answered Sep 18 '22 17:09

tomor