Search code examples
javascriptattributesselectors-api

Adding attribute to an element Javascript


I am JavaScript begginer and could use your help with the query below:

I had to find all li placed in nav tag in html. Now I have to check if li has data-direction attribute and if it doesn't - set this attribute to "top". I tried to do it using simple loop, but it doesn't seem to be working - I keep getting info from console that "direction is not defined" so it seems that it doesn't see "data-direction" as an attribute. Maybe I should indicate this attribute differently? Here is my code:

   var navLi = document.querySelectorAll("nav li");

   for (i = 0; i < navLi.length; i++) {
       if (navLi[i].data-direction === " ") {
       navLi[i].data-direction = "top";
      }
   }

Thanks in advance!


Solution

  • You're looking for hasAttribute()/setAttribute().

    for (i = 0; i < navLi.length; i++) {
       if ( !navLi[i].hasAttribute('data-direction') ) {
         navLi[i].setAttribute('data-direction', 'top')
      }
    }