简体   繁体   中英

How do I show/hide an <li> based on its text content using JavaScript?

I need to hide/show an <li> based on its text content. In the example below, I want to only show the list item that contains "content 1" and hide the rest of the list items. I'm sure there are several ways to do this. Would I need to convert the list to an array and then use the "includes" method, then append style display none/ display block using a conditional statement?

I would have several unordered lists on a page and therefore target them with the wrapper div's ID.

 <div id="myDiv">
    <ul class="myList">
        <li>content 1</li>   
        <li>content 2</li>  
        <li>content 3</li>   
        <li>content 4</li>     
     </ul>
   </div>

As in the subject you ask for a JavaScript solution, here is one. Iterate the li elements involved and set their display style depending on their text content:

 for (let li of document.querySelectorAll("#myDiv li")) { li.style.display = li.textContent === "content 1" ? "" : "none"; }
 <div id="myDiv"> <ul class="myList"> <li>content 1</li> <li>content 2</li> <li>content 3</li> <li>content 4</li> </ul> </div>

  1. If you want to achieve the text of an element, then you should use TextContent or innerHtml . textContent is more preferred because of some security issues and the latest syntax.
  2. You can also use indexOf() method to check if some string in the element exists or not. It is a string method. A similar syntax for this one is Node.textContent.indexOf("word") != -1) .
  3. Don't forget that you have more than one li tag so you must check the value of them with a loop(for). Preferably for let foo of bar .

 const li = document.querySelectorAll('li'); document.querySelector('button').addEventListener('click', () => { for (let x of li) { if (x.textContent === 'content1') { x.style.display = 'none'; } else { x.style.display = 'block'; } } });
 <ul> <li>content1</li> <li>content2</li> <li>content3</li> </ul> <button type="button">Hide</button>

My suggestion:

 [...document.querySelectorAll('.myList li')] .forEach(li => li.style.display = li.innerText === 'content 1' ? 'block' : 'none');
 <div id="myDiv"> <ul class="myList"> <li>content 1</li> <li>content 2</li> <li>content 3</li> <li>content 4</li> </ul> </div>

Alternatively:

 [...document.querySelectorAll('.myList li')] .forEach(li => { 'content 1' !== li.innerText && (li.style.display = 'none') });
 <div id="myDiv"> <ul class="myList"> <li>content 1</li> <li>content 2</li> <li>content 3</li> <li>content 4</li> </ul> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM