Home > OS >  How can i detect class name of an element using template literals inside querySelector
How can i detect class name of an element using template literals inside querySelector

Time:11-16

I have two navigation boxes where first one has a CSS Class .one and Second one is blank. For first navigation box, I given a border with JavaScript by detecting the class name .one. But I getting border for second navigation box too eventhough it don't have a class. Here i use template literals approach. I know that i can fix this using class name directly inside the querySelectorAll method as follows let li = document.querySelectorAll(".one > ul li");. But I need template literals solution which is most usefull for me to use some other projects too. Mainly i need to represent class name as a variable. Following is my code. Can anyone help me on this. Thanks in Advance!

let parents = document.querySelector(".one");
let li = document.querySelectorAll(`${parents.tagName} > ul  li`);
li.forEach((elem)=>{elem.style.border="1px solid red"}); 
nav {font-family:arial;width:15rem;}
    nav ul {list-style:none;padding:0;margin:1rem;padding-left:.5rem;}
    nav ul a {color:#777;text-decoration:none;padding:.5rem;}
<nav class="one">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a>
        <ul>
           <li><a href="#">Vision</a></li>
           <li><a href="#">Mission</a></li>
        </ul>
        </li>
        <li><a href="#">Contact</a></li>
    </ul>
</nav>

<br>

<nav>
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</nav>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Try replacing this line:

let li = document.querySelectorAll(`${parents.tagName} > ul  li`);

with this one:

let li = parents.querySelectorAll(`ul  li`);

The reason it doesn't work for you as you expected, is because you are matching all the elements with the query selector nav > ul li within the document, and you are completely ignoring the class name of the nav tag you have selected in parents variable.

Otherwise, you can simply do this instead:

let li = document.querySelectorAll(`.one > ul  li`);
li.forEach((elem)=>{elem.style.border="1px solid red"}); 

or just use the CSS:

.one > ul li {
   border: 1px solid red;
}

or if you want to select the first element (I don't know what are your intentions, but I'm guessing according to your code):

.one:first-child > ul li {
   border: 1px solid red;
}

CodePudding user response:

Don't need JavaScript. It can be possible by only CSS.

.one > ul > li { border: 1px solid red}

or in your JS change

let li = document.querySelectorAll(`${parents.tagName} > ul > li`);
  • Related