Home > Enterprise >  Why setAttribute is not setting class to li
Why setAttribute is not setting class to li

Time:11-15

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 >
      <h1 id="main-heading">Favourite Movie</h1>
      <ul>
        <li >The Matric</li>
        <li >Star Wars</li>
        <li >Harry Potter</li>
        <li >Lord of the Rings</li>
        <li >Marvel</li>
      </ul>
    </div>

CodePudding user response:

The order you do things matters.

  1. You find all the items matching .list-items
  2. You change their font size
  3. You create a new list item that matches .list-items

The item you create at step 3 didn't exist when you did the search at step 1 so wasn't changed by step 2.


Use a style sheet instead of inline style (which is what you modify with ...style.fontSize.

CodePudding user response:

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 >
      <h1 id="main-heading">Favourite Movie</h1>
      <ul>
        <li >The Matric</li>
        <li >Star Wars</li>
        <li >Harry Potter</li>
        <li >Lord of the Rings</li>
        <li >Marvel</li>
      </ul>
    </div>

  • Related