erzoolander
asked on
JQuery Syntax...
I have a number of elements that are set up like:
<div class="day fri past">
<a data-day="10" data-month="3" data-year="2017">10</a>
</div>
What would the syntax be in Jquery to output in a function the day, month and year?
something like:
?
Is that the right form, and how do you go about grabbing those data variables?
Thanks in advance!
<div class="day fri past">
<a data-day="10" data-month="3" data-year="2017">10</a>
</div>
What would the syntax be in Jquery to output in a function the day, month and year?
something like:
$('.day a').click(function(){
alert("day is"+?);
alert("month is"+?);
alert("year is"+?);
});
?
Is that the right form, and how do you go about grabbing those data variables?
Thanks in advance!
First solution.You can assigne an id into separate element and work as follow:
HTML
JQuery:
Second without setting ID attr:
HTML
JQuery:
HTML
<div class="day fri past">
<a data-day="10" data-month="3" data-year="2017" id="date_1" >10</a>
</div>
<div class="day fri past">
<a data-day="20" data-month="31" data-year="2017" id="date_2" >10</a>
</div>
<div class="day fri past">
<a data-day="12" data-month="3" data-year="2017" id="date_3">10</a>
</div>
JQuery:
(function(){
var day=$('#date_1').data('day');
var month=$('#date_1').data('month');
var year=$('#date_1').data('year');
alert(day+'\n'+month+'\n'+year);
})();
Second without setting ID attr:
HTML
<div class="day fri past">
<a data-day="10" data-month="3" data-year="2017" >10</a>
</div>
<div class="day fri past">
<a data-day="20" data-month="31" data-year="2017" >10</a>
</div>
<div class="day fri past">
<a data-day="12" data-month="3" data-year="2017" >10</a>
</div>
JQuery:
($(function(){
var allAnchorElements=document.querySelectorAll('a');
for(var i=0;i<=allAnchorElements.length;i++){
var dayi=allAnchorElements[i].dataset.day;
var monthi=allAnchorElements[i].dataset.month;
var yeari=allAnchorElements[i].dataset.year;
alert(dayi+'\n'+monthi+'\n'+yeari);
}
}));
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Not to be snarky, but can you tell me why my answer was not accepted? You specifically requested a jQuery solution, which is what I provided, as Julian pointed out. It will help me to present better answers in the future if I know why.
Open in new window