简体   繁体   中英

Get Child Element Value with Mootools

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

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

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);
});

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?

这是你想要的:

$$('img[src=share.jpg]').getParent().set('class', 'newClass');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM