Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why setAttribute is not setting class to li

Actually, I’m learning DOM Manipulation. As you can see, I created the li element but the issue is it is not applying the fontSize to the li.

const title = document.querySelector("#main-heading");

title.style.color = "red";

const listItems = document.querySelectorAll(".list-items");
  
for (i = 0; i < listItems.length; i++) {
    listItems[i].style.fontSize = "2rem";
}
const ul = document.querySelector("ul");
const li = document.createElement("li");

ul.append(li);
li.innerText = "X-men"
li.setAttribute('class' , 'list-items' )

  
   <div class="container">
      <h1 id="main-heading">Favourite Movie</h1>
      <ul>
        <li class="list-items">The Matric</li>
        <li class="list-items">Star Wars</li>
        <li class="list-items">Harry Potter</li>
        <li class="list-items">Lord of the Rings</li>
        <li class="list-items">Marvel</li>
      </ul>
    </div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Remove setting the font-size value inside for loop. Instead have it as separate css.

.list-items {
  font-size: 2rem;
}

Append the newly created li after the class is added.

ul.append(li);

Forked Example:

const title = document.querySelector("#main-heading");

title.style.color = "red";

const listItems = document.querySelectorAll(".list-items");
  
const ul = document.querySelector("ul");
const li = document.createElement("li");

li.innerText = "X-men"
li.setAttribute('class' , 'list-items');

ul.append(li);
.list-items {
  font-size: 2rem;
}
<div class="container">
      <h1 id="main-heading">Favourite Movie</h1>
      <ul>
        <li class="list-items">The Matric</li>
        <li class="list-items">Star Wars</li>
        <li class="list-items">Harry Potter</li>
        <li class="list-items">Lord of the Rings</li>
        <li class="list-items">Marvel</li>
      </ul>
    </div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading