Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing DOM elements without id

Tags:

javascript

dom

i have a page around 500 div as below.

<div onclick='test()' class='test>
     <ul class='innermenu'>
       <li>1</li>
       .....
      </ul>
  </div>

when the test function is called it need to hide the menu (innermenu) who calls that function.

my problems are

  1. uniquely identify the div without using id

  2. How to hide only the particular ul alone.

like image 383
ArK Avatar asked Dec 03 '22 13:12

ArK


2 Answers

OK, first the quick fix, though it is not the best way to use JS on your page:

Change the call to this:

<div onclick="test(this);" class="test">

Then, in test, use this:

function test(el){
   var uls = el.getElementsByTagName('ul');
   for(var i = 0; i < uls.length; i++){
      if(uls[i].className == 'innermenu'){
         uls[i].style.display = "none";
         break;
      }
   }
}

This will hide just the child ul of the div that is clicked.

A better way

OK, for the longer answer. Either attach the events after the fact using attachEvent and addEventListener or use a library like jQuery to help you out. Here is the raw solution:

Set up your HTML this way (no onclick):

<div class="test">

And then at the very end of your HTML put this:

<script type="text/javascript">
    var divs = document.getElementsByTagName('div');
    function test(){
      var uls = this.getElementsByTagName('ul');
      for(var i = 0; i < uls.length; i++){
         if(uls[i].className == 'innermenu'){
            uls[i].style.display = "none";
            break;
         }
      }
    };

    for(var i = 0; i < divs.length; i++){
      var div = divs[i];
      if(div.className !== "test") continue;
      if(window.addEventListener){
         div.addEventListener( 'click', test, true ); //FF, Webkit, etc
      } else if (window.attachEvent) {
         div.attachEvent('onclick', test); // IE
      } else {
         div.onclick = test; // Fallback
      }
    }
</script>

Now, you don't have JavaScript code in your HTML, and you can get rid of the extra parameter on the test function.

like image 187
Doug Neiner Avatar answered Dec 21 '22 07:12

Doug Neiner


There is a method

document.getElementsByClassName

but it isn't supported in all browsers.

javascript

function test(elem)
{
    var childElem = elem.children[0];
    childElem.style.display = 'none';
}

<div onclick='test(this)' class='test'>
    <ul class='innermenu'>
        <li>1</li>
        <li>2</li>
    </ul>
</div>

If you can use jQuery then you can do something like this

$("div.test").click(function(){
    $(this).find("ul.innermenu").hide();
});
like image 29
rahul Avatar answered Dec 21 '22 09:12

rahul