Select Elements in nested Divs using JQuery
- by PIKP
I have the following html markup inside a Div named item and I want to select all the elements (inside nested divs) and clear the values. As shown in following given Jquery I have managed to access elements in each Div by using.children().each(). But the the problem is .children().each()goes one level down at a time from the parent div, so I have repeated the same code block with multiple .children() to access the elements inside nested Divs, can anyone suggest me a method to do this without repeating the code for N number of nested divs .
html markup
<div class="item">
<input type="hidden" value="1234" name="testVal">
<div class="form-group" id="c1">
<div class="controls ">
<input type="text" value="Results" name="s1" maxlength="255" id="id2">
</div>
</div>
<div class="form-group" id="id4">
<input type="text" value="Results" name="s12" maxlength="255" id="id225">
<div class="form-group" id="id41">
<input type="text" value="Results" name="s12" maxlength="255" id="5">
<div class="form-group" id="id42">
<input type="text" value="Results" name="s12" maxlength="255" id="5">
<div class="form-group" id="id43">
<input type="text" value="Results" name="s12" maxlength="255" id="id224">
</div>
</div>
</div>
</div>
</div>
My Qjuery script
var row = $(".item:first").clone(false).get(0);
$(row).children().each(function () {
updateElementIndex(this, prefix, formCount);
if ($(this).attr('type') == 'text') {
$(this).val('');
}
if ($(this).attr('type') == 'hidden' && ($(this).attr('name') != 'csrfmiddlewaretoken')) {
$(this).val('');
}
if ($(this).attr('type') == 'file') {
$(this).val('');
}
if ($(this).attr('type') == 'checkbox') {
$(this).attr('checked', false);
}
$(this).remove('a');
});
// Relabel or rename all the relevant bits
$(row).children().children().each(function () {
updateElementIndex(this, prefix, formCount)
if ($(this).attr('type') == 'text') {
$(this).val('');
}
if ($(this).attr('type') == 'hidden' && ($(this).attr('name') != 'csrfmiddlewaretoken')) {
$(this).val('');
}
if ($(this).attr('type') == 'file') {
$(this).val('');
}
if ($(this).attr('type') == 'checkbox') {
$(this).attr('checked', false);
}
$(this).remove('a');
});