Question

I have some Divs:

<div id="content">
    <div class="c" id="1">
        <div id="xyz">dont care</div>
        <div id="texts1">
            <div name="check"> ContentText </div>  
        </div>
    </div>
    <div class="c" id="2">
        <div id="xuyz">dont care</div>
        <div id="texts2">
            <div name="check"> ContentText </div>  
        </div>
    </div>
</div>

I want to iterate through all elements of the "c" class. Then I want to check, if the Div elements named "check" of each "c" element contains special text.

If true, then manipulate the "c" element (which contains the special text)

I tried something like this:

var ele = document.getElementsByClassName("c");
for(var i=0;i<ele.length;i++)
{
 var check = ele[i].getElementsByName("check");
 if(check.innerHTML ....)
}

But thats not working :/ Log from Firefox:

TypeError: ele[i].getElementsByName is not a function

Where is my mistake?

Was it helpful?

Solution

A simple querySelectorAll() should do the trick:

var check = document.querySelectorAll('.c [name="check"]');

And as stated in a comment already, only document has getElementsByName method.

OTHER TIPS

With jQuery this is very simple -

$('[name="check"]:contains("your special text")')

With jQuery (you have tagged it with it as well)

$(document).ready(function () {
    $('div.c').find('div[name="check"]').each(function(){
        // here check HTML and do needed manipulations
        if($(this).html() == 'ContentText'){
            $(this).closest('div.c').children().first().html('I CARE');
        }
    });
}); 

see jSFiddle -> http://jsfiddle.net/ApfJz/32/

Here is a modification of your code to make it work as intended

var ele = document.getElementsByClassName("c");
for (var i = 0; i < ele.length; i++)
{
    if (ele[i].getAttribute('name') === "check") {
        // do something with matching elements here
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top