Search code examples
javascriptinnerhtml

Getting Error While setting icon in List : Cannot set property 'innerHTML' of undefined


Getting Error While setting icon in Top 3 row of list

$(document).ready(function() {
  var navItems = document.getElementsByClassName("icon");
  for (var i = 0; i < 3; i++) {
    navItems[i].innerHTML = '<i class="fa fa-gift" aria-hidden="true" style="color: #ff8944;font-size: 19px;"></i>'
  }
});

Solution

  • When using plain JS DOM manipulation, such errors are common if such an element could not be retrieved from the DOM (since it's like doing: undefined.innerHTML = )

    • No need to loop anything if you use $("selector").html() jQuery will loop your elements collections internally.
    • Use jQuery (since you're already using it) - it will fail silently if no .icon elements were found
    • Don't use inline style attributes

    jQuery(function($) {
      $(".icon").html('<i class="fa fa-gift" aria-hidden="true"></i>')
    });
    .icon .fa {
      color: #ff8944;
      font-size: 19px;
    }
    No ".item" in DOM - Will not show errors.
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>