innerHTML not working properly when used on a jQuery object

后端 未结 3 550
既然无缘
既然无缘 2020-12-12 04:01

This code isn\'t working as expected. It is not showing any text inside of span.day where it should be showing today\'s day (Tuesday at the time of writing). It is also not

相关标签:
3条回答
  • 2020-12-12 04:39

    You are trying to invoke JS properties on jQuery objects.

    For example innerHTML

    And you are trying to invoke that on a jQuery object.

    $('#showLessHours span.day').innerHTML
    

    Should be

    $('#showLessHours span.day')[0].innerHTML
    

    or

    $('#showLessHours span.day').html(weekday[today]);
    

    And in your each loop item is a JS object and you are trying to add a class using jQuery. Convert that to jQuery object first .

    item.addClass('currentDay');
    item.removeClass('currentDay');
    

    should be

    $(item).addClass('currentDay');  or $(this).addClass('currentDay');
    $(item).removeClass('currentDay'); or $(this).removeClass('currentDay')
    

    Instead you can use the $(this) as well instead of $(item) object inside the callback as both refer to the same objects.

    Another small suggestion is why do you want to mix vanilla JS and jQuery when jQuery is included and you want to use that in your application.

    jsFiddle

    0 讨论(0)
  • 2020-12-12 04:39

    In addition to what Sushanth said, you are also trying to invoke jQuery methods on javascript objects.

    item.addClass
    

    should by

    $(item).addClass
    
    0 讨论(0)
  • 2020-12-12 04:41

    Because .innerHTML isn't a jquery function. You can use .html() to achieve what you are trying to do. Alternatively, if you REALLY want to use .innerHTML, you can use .get() to get the actual DOM element, and then use .innerHTML but... I wouldn't recommend it.

    I believe this edited fiddle solves your problem. Relevant code:

    $('#showLessHours span.day').html(weekday[today]);
    //...
    if(item.html() != '') {     
        alert('item.text:' +item.text());
        alert('weekday[today]'+item.text().indexOf(weekday[today]));
        if(item.html().indexOf(weekday[today])!=-1) {
    //...
    
    0 讨论(0)
提交回复
热议问题