0

I'm trying to have the days of the week appear within my H2 elements but the console says "cannot read property of fday undefined" Below is the HTML elements I'm trying to append to and the JS i'm using to do it

<div class="flex-container col-xs-6" id="weekDay">
    <h2 data-fday="1"></h2>
    <h2 data-fday="2"></h2>
    <h2 data-fday="3"></h2>
    <h2 data-fday="4"></h2>
    <h2 data-fday="5"></h2>
</div>

for (var i = 0; i < 6; i++) { //Begin loop - loop over the object's next 5 days
    const weekly_forecast = data.daily.data;
    let today = moment().format('D MMM, YYYY');//Format the date in the form Day / Month / Year from moment.js library
    const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

    $('#day_'+[i]).append("<h3>"+weekly_forecast[i].apparentTemperatureMax + "<br></h3><P>" + weekly_forecast[i].summary + "</p>"); //append a <h2> within that div containing the day and <p> containing the high and low temperature for the day
        //Get the day of the week...
    let a = new Date(today); //parse current date
    let nextDay = weekday[a.getDay()+i]; //(get the day of the week)
    const dayData = $("#weekDay > h2").dataset.fday; //accessthe data-attribute of each H2 within #weekday
    if (dayData = [i]) {    //if the data attribute of the H2 element === i
        $(this).append(nextDay);    //append the current day of the week in the H2
    }

    console.log(nextDay);

}
3
  • check if $("#weekDay > h2") actually returns anything Commented Jan 8, 2017 at 23:13
  • .data('fday') should work Commented Jan 8, 2017 at 23:16
  • @Ted the console shows [h2, h2, h2, h2, h2, prevObject: r.fn.init[1] logged out 6 times Commented Jan 8, 2017 at 23:17

2 Answers 2

1

dataset is not a jQuery object property, it is a dom element property.

Also you need to target the proper element index within the loop

Try changing

$("#weekDay > h2").dataset.fday

To

$("#weekDay > h2").eq(i).data('fday');

Or to access as dom node property

$("#weekDay > h2")[i].dataset.fday
Sign up to request clarification or add additional context in comments.

Comments

0

There are two ways of doing it using PURE JS. Either using dataset or using the getAttribute method.

var test = document.getElementsByTagName('li');
console.log(test[1].dataset.id);
var dataText = test[0].dataset.id + " " + test[1].dataset.id;
document.getElementById('target').innerHTML = dataText;


var dataTextAnotherApproach = test[1].getAttribute('data-id');
document.getElementById('target2').innerHTML = dataTextAnotherApproach;
<div id="test">
  <ul>
    <li data-id="data 1">Hello</li>
    <li data-id="data 2">Hello 2</li>
  </ul>
</div>
<div id="target"></div>
<div id="target2"></div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.