How do I remove all classes in my li elements?

Note, I'm using React. How do I delete all the classNames in li that have turnRed?

<li>
    <a href='/test'>Test1</a>
    <ul className="t1"
        id="deleteRed">
        <li>t1</li>
        <li className="turnRed">t2</li>
        <li className="turnRed">t3</li>
        <li className="turnRed">t4</li>
        <li className="turnRed">t5</li>
    </ul>
</li>

Note, I've tried

document.getElementById("deleteRed").children.query.className = "";

However, I get an error.

2 answers

  • answered 2018-11-08 01:14 Ele

    I think you need to change the attribute className to class.

    You can use the function Document.querySelectorAll which returns a static (not live) NodeList.

    Using the attribute class the selector is very simple and not only that but also you can use the property classList which provides the list of classes in an element. That property has few methods, one of them is the method remove() who removes classes.

    Array.from(document.querySelectorAll('#deleteRed li.turnRed'))
         .forEach(li => li.classList.remove('turnRed'));
    .turnRed{
      color: red
    }
    <li>
      <a href='/test'>Test1</a>
      <ul class="t1" id="deleteRed">
        <li>t1</li>
        <li class="turnRed">t2</li>
        <li class="turnRed">t3</li>
        <li class="turnRed">t4</li>
        <li class="turnRed">t5</li>
      </ul>
    </li>

    In case you really need that attribute className, you can use a similar approach

    console.log('Before remove:', document.querySelectorAll('#deleteRed li[className="turnRed"]').length);
    Array.from(document.querySelectorAll('#deleteRed li[className="turnRed"]'))
         .forEach(li => li.removeAttribute('className'));
    console.log("After remove:", document.querySelectorAll('#deleteRed li[className="turnRed"]').length);
    <li>
      <a href='/test'>Test1</a>
      <ul class="t1" id="deleteRed">
        <li>t1</li>
        <li className="turnRed">t2</li>
        <li className="turnRed">t3</li>
        <li className="turnRed">t4</li>
        <li className="turnRed">t5</li>
      </ul>
    </li>

  • answered 2018-11-08 05:20 John Hooper

    Sorry this was getting a little long for a comment so putting it down here as an answer.

    since you're using react you really shouldn't be using document.getElementById at all. ideally the logic for what is red or not would be stored either in your component's state or better yet in the state of your application via redux or some other state management tool.

    here is an example that toggle's what object is red. you could add more complex logic or better yet pass a callback into the child! check out the handleClick action in the parent and the clickAction in the child. see how we're passing the index value from the child back to the parent so it can update the state in the right spot? in a real world situation you would likely use an id, but for this purpose an index will work just as well.

    let me know if anything is confusing, or you need help understanding any part of this answer!

    // takes a list of items and adds the isRed classname if its red
    const RedList = ({items, clickAction}) => {
      return (
        <ul>
          {items.map(
            (item, index) => {
              // set the classnames
              let className = item.isRed ? 'isRed' : '';
              if (item.isBold) {
                className = className + ' isBold';
              };
              return (
                <li
                  onClick={() => clickAction(index)}
                  key={index} className={className}>
                  {item.name}
                </li>
              );
            })
          }
        </ul>
      )
    }
    
    // this container handles the logic for setting if an object is red or not
    class Container extends React.Component{
      constructor(props){
        super(props);
        this.state={
          items: [
            {
              isRed: false,
              name: 't1',
              isBold: false,
            },
            {
              isRed: true,
              name: 't2',
              isBold: false,
            },
            {
              isRed: true,
              name: 't3',
              isBold: false,
            },
            {
              isRed: true,
              name: 't4',
              isBold: false,
            },
            {
              isRed: true,
              name: 't5',
              isBold: false,
            },
            {
              isRed: true,
              name: 't6',
              isBold: false,
            },
          ]
        };
      }
      
      deleteRed = () => {
        const newState = this.state.items
          .map(item => ({
            isRed: !item.isRed,
            name: item.name,
            isBold: item.isBold
          }));
        this.setState({items: newState});
      }
      
      // this gets passed into the child and accepts an 
      //index value
      handleClick = (itemIndex) => {
        const newState = this.state.items
          .map((item, index) => {
            if(index === itemIndex) {
              return {
                name: item.name,
                isRed: item.isRed,
                isBold: !item.isBold,
              };
            } else {
              return item;
            }
          });
        this.setState({items: newState});
      }
      
      render(){
        return (
          <li>
            <button onClick={this.deleteRed}>Test1</button>
            <ul class="t1" id="deleteRed">
              <RedList 
                items={this.state.items}
                clickAction={(index) => this.handleClick(index)}
              />
            </ul>
          </li>
        );
      }
    }
    
    
    
    ReactDOM.render(<Container/>, document.getElementById('root'));
    .isRed {
      color: red;
    }
    
    .isBold {
      font-weight: bold;
      font-size: 24px;
    }
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>