Search code examples
javascriptjqueryprototypejs

How to loop though elements based on part of the dom name


I want to hide all the elements on the page that end in _dropMenu via javascript...so this is what i have

window.onload = function() {
  hideNav();
};

    function hideNav(){
      myArray = element("_dropMenu");// this is what need changing 
      for (i=0;i<=5;i++)
      {
         i.style.visibility = 'hidden';
      }
    }

This is obviously wrong but how do I first get all the elements on the page that end with _dropMenu then loop through them and set them to hidden... I would prefer javascript since I only have prototype on the page but if I need to add jquery I will...


Solution

  • jQuery has a selector for finding elements that have an attribute that ends with a given string:

    $('[id$="_dropMenu]')
    

    This will be faster if you can narrow it by an element type (e.g. if all the elements you care about are divs, or some such) but will work as is.

    Behind the scenes, jquery is just looping through a given set of elements, and checking whether element["id"].substring(element["id"].length-"_dropMenu".length)==="_dropMenu".