Search code examples
javascriptprototypejs

when open the page,why can't hide the content?


I have added the Prototype library to my site, then add the following code.when i open the page, i want to all the content in the ul are hidden.

 Event.observe(window, 'load', function() {
   $$('.block-category li.parent ul').hide() //why this line doesn't work
    $$('.block-category li.parent > a span').each(function (element) {
        element.observe('click', function (e) {
            e.element().up().next('ul').toggle();
            e.preventDefault();
        });
    });
});

html:

    <div class="block block-category">
    <li class="level-top  parent">
    <a href="example.com/...."><span>text one</span></a>
    <ul> //the 1 ul
    <li><a><span>....</span></a></li>
    <li><a><span>....</span></a></li>
    <li><a><span>....</span></a></li>
    <li><a><span>....</span></a></li>
    </ul>
    </li>

    <li class="level-top"><a href="..."><span>....</span></a></li>


  <li class="level-top  parent">
    <a href="example.com/...."><span>text two</span></a>
    <ul> //the 2 ul
    <li><a><span>....</span></a></li>

    </ul>
    </li>
  <li class="level-top  parent">
    <a href="example.com/...."><span>text three</span></a>
    <ul>
    <li><a><span>....</span></a></li>
    <li><a><span>....</span></a></li>
    </ul>
    </li>
    </div>

thank you.


Solution

  • The $$() method returns a list of elements that match that CSS selector - if you want to iterate over them and run the same method use the invoke() method

    $$('.block-category li.parent ul').invoke('hide');
    $$('.block-category li.parent ul').invoke('observe','click',function(){
         alert('element was clicked');
    });
    

    If you need to do more than just run a single method use the each() method

    $$('.block-category li.parent ul').each(function(item){
        item.hide();
        //item.update('new content');
        //etc
    });