views:

51

answers:

3

I'm trying to change a class by first discovering if it is the parent object to a particular image using Mootools (clients previous web developer seemed to have it in for me). I can't seem to find much good documentation on the subject.

<div class="textwidget">
<img src="share.jpg">
</div>

So far I've managed to locate all the divs with the class 'textwidget' using:

var obs = $$('.textwidget');

Now I need to cycle through them and discover which hosts a child node with the src listed above...

for(var i=0;i<obs.length;i++){
    if(obs[i].childnode.src == 'share.jpg'){ // <-- non mootools syntax
        obs[i].class = 'new class'; // <-- non mootools syntax.
    }
}

i'd like to run a loop like this, but in mootools speak of course. Anyone familiar with the correct syntax?

Thanks -J

+1  A: 

I think what you want is something like:

for(var i=0;i<obs.length;i++){
    if(obs[i].getChildren()[0].getProperty('src') == 'share.jpg'){ // <-- mootools syntax
        obs[i].setProperty('class','new class'); // <-- mootools syntax.
    }
}

You can find more details here:

http://mootools.net/docs/core/Element/Element

edl
you rock, thank you.
Jascha
You should probably use addClass/removeClass when manipulating the class property, instead of setting it directly. Then you don't have to worry about wiping the other classes off if you apply a style later.
Nathan Reed
+1  A: 

you could do something like this via a selector / parent combo:

document.getElements("div.textwidget img[src=share.jpg]").getParent("div.textwidget");

http://www.jsfiddle.net/MBc37/4/

or you can be more thorough / longwinded...

// css selector, divs array filtered by existance of a child img
results.mixedFilter = document.getElements("div.textwidget").filter(function(el) {
    return el.getElement("img[src=share.jpg]");
});

// checking vs img src properties of all child imgs
results.longwinded = [];
document.getElements("div.textwidget").each(function(el) {
    var imgs = el.getElements("img");
    if (!imgs.length) return;
    if (imgs.some(function(im) {
        return im.get("src") == "share.jpg";
    })) results.longwinded.push(el);
});
Dimitar Christoff
A: 

What you want to do here is filter the array of elements like this:

$$('.text-widget').filter(function(e) {
    var child_img = e.getFirst('img');
    return $defined(child_img) && child_img.get('src') == 'share.jpg'
});

If the function passed to 'filter' returns true the item gets included.

You could also use selectors as one of the other answers mentioned. Although there might be performance issues with using them in that way?

Nathan Reed