1

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!

2 Answers 2

2

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')
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

getAttribute() will return null or an empty string so you need to use the hasAttribute() method to handle the null case.

for (var item of document.querySelectorAll("nav li")) {
  if (!item.hasAttribute("data-direction") || item.getAttribute("data-direction").trim() === "") {
    item.setAttribute("data-direction", "top");
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.