Hi I am updating a website someone else made.
I have a calendar and each date in the calendar has the same values
<a class="bkiavanae" href="#" id="selectiondate" data-dn="02 May 2024" data-ct="1-a">2<p style="font-size: 10px">£110</p></a>
All have the same class and id value.
I have placed an event listening to the onClick for any clicks on the class bkiavanae which is working fine.
But I need the on click to capture the value of the data-dn value. So in this example need it to return 02 May 2024
var calenderSelection = document.getElementsByClassName("bkiavanae");
for (var i = 0; i < calenderSelection.length ; i++) {
calenderSelection[i].addEventListener("click",
function (event) {
event.preventDefault();
//alert("hello");
},
false);
}
4
Answers
Use
event.target.getAttribute
to retrieve the value of thedata-dn
attribute:You can get that value via
this.getAttribute("data-dn")
:!!!WARNING!!!
Reusing the same
id
for multiple elements is invalid HTML, so I strongly advise you to either remove the ids of these tags, or, if you need someid
for them, make sure they are unique in the page.Your html code is using a dataset, so you can use the dataset property to access the value in your Javascript code.
Don’t forget to handle the case where the user clicks on the p element (£11 in your example). With @john’s answer you will get a null if you click on the p element. In this snippet you will get the date.
You can use the dataset property on the element to get any of the
data-*
attributes by it’s name.If you need the id (
id="selectiondate"
) they should be unique. Either delete the attribute OR turn int onto adata-*
attribute likedata-id="selectiondate"
. In the example I use it for testing if it is the right element that was clicked.