views:

180

answers:

2

Hi there,

I am trying to get some information of a child element of an li using mootools, essentially my html looks like this,

<li><a href="/home" id="home" class="nav-link">Home</a></li>

I am wanting to be able get the id, class and href of the a tag using mootools, so far my javascript looks similar to this,

$$('.rate').each(function(element,i){
element.addEvent('click', function(){
    var myStyles = ['nostar', 'onestar', 'twostar', 'threestar', 'fourstar', 'fivestar', 'sixstar', 'sevenstar', 'eightstar', 'ninestar', 'tenstar'];
    myStyles.each(function(myStyle){
        if(element.getParent().hasClass(myStyle)){
            element.getParent().removeClass(myStyle)
        }
    });     
    myStyles.each(function(myStyle, index){
        if(index == element.id){
            element.getParent().toggleClass(myStyle);

            var req = new Request({
                method:'post',
                url: '/recipes/save',
                data: {'rating' : element.id},
                onRequest: function(){ alert('Request made. Please wait...');},
                onComplete:function(response){ alert('Response:' + response);}
            }).send();
            alert('Clicked '+element.id);
            alert(element.getChildren().get('href');
        }
    });     

});

});

The final alert in the script is my attempt to the child of the li(element) and its href.

A: 

All these properties are exposed natively as:

<elem>.id
<elem>.href
<elem>.className

If element contains a reference to the <li> DOM object, you can get the child <a> and all three properties as:

var anchor = $$("li").getFirst("a");
anchor.id
anchor.href
anchor.className

Or as Oskar says, if you don't want to worry about cross-browser issues, a better alternative is to use the get method in Element/Elements to retrieve these:

anchor.get('id')
anchor.get('href')
anchor.get('class')
Anurag
`$$('li')` - notice the double-dollar.Also, it's safer to do it the MooTools way:`el.get('id')`, `el.get('href')` and `el.get('class')`
Oskar Krawczyk
thanks Oscar, I always forget the double dollar!
Anurag
+1  A: 

This statement of yours is incorrect if(index == element.id){ ..., index is always a number, you need to replace it with myStyle. Proof: http://jsfiddle.net/fJDZJ/

After that just do a el.get('id'), el.get('href') and el.get('class');

Or el.getElement('a').get('id'); if you need to get the ID of the child A.

Oskar Krawczyk