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>
Node.textContent.indexOf("word") != -1)
. 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.