Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  174] [ 2]  / answers: 1 / hits: 72677  / 11 Years ago, tue, april 9, 2013, 12:00:00

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?


More From » javascript

 Answers
4

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.


[#79009] Monday, April 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cherish

Total Points: 734
Total Questions: 94
Total Answers: 86

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
cherish questions
Tue, Jan 25, 22, 00:00, 2 Years ago
Mon, Oct 5, 20, 00:00, 4 Years ago
Mon, Jun 22, 20, 00:00, 4 Years ago
;