views:

56

answers:

4

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!

A: 

You can use CSS in JavaScript.

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

Plus, check out Mozilla JavaScript reference.

Todd Moses
A: 

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';
Soufiane Hassou
Thanks!! But with my timeframe to get this done, I'm sorta looking for the answer and not a lead to find the answer. If I wasn't under the gun, I'd do it the "exploratory" way.
Loony2nz
@Loony2nz: you don't have to explore this one. This is the right way.
Crescent Fresh
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';
Soufiane Hassou
ajji you are a godsend! thank you so much!
Loony2nz
A: 

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";
}
Alex C
i think you mean "if (i > 2)". also, i believe element.childNodes will return additional text nodes for whitespace (if there is any).
ob
OB is right. it is I > 2 and I am getting 29 childnode elements, instead of 14.
Loony2nz
heh yeah my mistake
Alex C
A: 

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';
      }
   }
}
Bryan Kyle