Search code examples
javascriptmootools

Select list item by class name from div


I have had a search and I'm still a bit puzzled.

I am trying to select a list element by class name from a div using mootools.

The html is

<div class="someDiv">
  <ul class="aList">
    <li class="listItem0">
      <a href="#" class="nameVaries">
      </a>
  </li>
    <li class="listItem1">
      <a href="#" class="nameVaries">
      </a>
    </li>
  </ul>
</div

I have tried using check = $(event.target)getElement('a').getProperty('class'); and sending check to the console to check what I have but it is a null value. I'm needing pointed in the right direction. I'm pretty sure I need to select the div from the dom and then check the child elements for the class name and compare that to a value and then I can continue with whatever action I'd like.


Solution

  • A bit unclear what you are trying to do, but please comment if I guess wrong.

    You just missed a dot in your code. To get the class of the a element when you click the someDiv element you can use:

    document.getElements('div.someDiv').addEvent('click', function () {
        var check = $(event.target).getElement('a').getProperty('class');
        console.log(check);
    });
    

    You can also use var check = this.getElement('a').getProperty('class');

    Demo here

    EDIT (after your comment):

    Ok, from your comment I think what you want is to listen to the click on the a element. It might be good to also prevent the link redirect from happening if you have code to run. So try this:

    document.getElements('a').addEvent('click', function (event) {
        event.preventDefault();
        var check_this = this.getProperty('class');
        console.log(check_this);
    });
    

    You can then do the redirect with window.location.href = this.getProperty('href'); when you are done with the code you need to run.

    Check the demo for example with links with url.