How to access the data-weekday property of the div element with javascript?

Asked

Viewed 82 times

1

How to access the data-weekday property of the div element with javascript?

<div style="display: none;" id="weekday" data-weekday="7"></div>

2 answers

2


You can use the .dataset:

const weekDay = document.getElementById('weekday').dataset.weekday;
console.log(weekDay); // 7
<div style="display: none;" id="weekday" data-weekday="7"></div>

Or read the attribute directly:

const weekDay = document.getElementById('weekday').getAttribute('data-weekday');
console.log(weekDay); // 7
<div style="display: none;" id="weekday" data-weekday="7"></div>

0

To get an attribute from your div just use getAttribute("data-weekday"); specified in w3schools. Follow the demo.

var x = document.getElementById("weekday").getAttribute("data-weekday");
alert(x);
<div style="display: none;" id="weekday" data-weekday="7"></div>

With Jquery

var x = $("#weekday").attr("data-weekday");
alert(x);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="display: none;" id="weekday" data-weekday="7"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.