Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery select child through random generated divs

I have a bunch of generated divs that I'd like to grab a specific child of.

Each one is roughly set up like this:

<div id="generated-row-N>
    <div class="seriously-generated-crap">
        <div id="still-seriously-generated-crap-N">
            <input name="child-to-select-N">
        </div>
    </div>
</div>

Where N is a counter

I'm not well versed in all the different kinds of jQuery selectors, what I've attempted is a combination of the "begins with" selector and the "child" selector.

$("div[id^=generated-row-] > input[name^=child-to-select-]").each(function(){
    // stuff I'm going to do to each input child
});

I assume my error is it's thinking the child is a direct child of the parent with no elements in between. Is there a way to get through the two other divs and grab a child regardless of how many levels deep it is?

note: I'm not listing the other childs because the generated class and id names are not reliable to use.

Thanks in advance. I haven't had much luck finding similar topics on SO, if this is a duplicate, please let me know.

like image 640
domdomcodecode Avatar asked Aug 08 '26 23:08

domdomcodecode


2 Answers

> is the immediate children selector, just omit it.
And also wrap the values of your attributes with single quotes ''

$("div[id^='generated-row-']  input[name^='child-to-select-']")
like image 170
Fabrizio Calderan Avatar answered Aug 11 '26 11:08

Fabrizio Calderan


You need to use descendant selector instead of child selector

$("div[id^=generated-row-] input[name^=child-to-select-]").each(function(){
    // stuff I'm going to do to each input child
});

when you use a child selector it will search only the direct children of the target parent, in your case the input element is coming at the 3rd level means it is an descendant element not a child


Also to make it much easier apply class like

<div id="generated-row-N" class="generated-row">
    <div class="seriously-generated-crap">
        <div id="still-seriously-generated-crap-N">
            <input name="child-to-select-N" class="child-to-select">
        </div>
    </div>
</div>

then

$(".generated-row input.child-to-select").each(function(){
    // stuff I'm going to do to each input child
});
like image 44
Arun P Johny Avatar answered Aug 11 '26 13:08

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!