简体   繁体   中英

How do I show X number of LI from a list using javascript (no frameworks)?

I have a menu that is being populated by a server and I have no access to the server. So I am limited to doing this on the client side.

Right now there is a dropdown menu on the navigation with 14 choices. The client wants to only show 3 of them.

They're not using any frameworks like jquery or mootools, so I have to do this the old-fashioned way, yet, I'm at a wall.

<ul id='mylist'>
<li>option 1</li>
<li>option 2</li>
<li>option 3</li>
<li>option 4</li>
<li>etc</li>
</ul>

What's the javascript code to add display:none to list items 4-14?

(this also helps me get back to JS fundamentals and not relying on frameworks).

Thanks for your help!

You can use CSS in JavaScript.

Here is the reference: http://codepunk.hardwar.org.uk/css2js.htm

Plus, check out Mozilla JavaScript reference.

You can do a getElementById() to get the menu, then getElementsByTagName() for the LIs which will return an array (say items[]). And then change style for items[3] to items[13].

Edit

I made you a small code:

var menu = document.getElementById('mylist');
var LIs = menu.getElementsByTagName('li');
for(var i = 3; i< 14; i++)
    LIs[i].style.display='none';

Something like this? (off the top of my head, sorry if it's sloppy)

var children= document.getElementByid("mylist").childNodes;
for (var i = 0; i < children.length; i++){
    if (i < 2) children[i].style.display = "none";
}

You'll have to grab the child nodes of the list and set the style.display property of each of the ones that your client doesn't want to see to none . This doesn't sound too tricky, but the child node collection can contain elements, text nodes, comments, etc, so you'll have to check to make sure that the node is an element with a tagName of "LI" before processing. Below is some code that should do the trick.

for (var node = document.getElementById('mylist').firstChild; node != null; node = node.nextSibling) {
   if (node.type === 1 && node.tagName.toUpperCase() === "LI") {
      if (/* node is not one of the ones your client wants to see */) {
         node.style.display = 'none';
      }
   }
}

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