I don't know how to count the div's of subchildren inside the parent div maybe someone can help me with this. I'm not that good in javascript or in Jquery.
Here's my code:
$(function () {
var parent = document.getElementById('parent').children;
var cnt = 0;
if (parent) {
var match = 'child';
for (var i = 0; i < parent.length; i++) {
var temp = parent[i].getAttribute('id');
if (temp.indexOf(match) == 0) {
cnt++;
}
}
}
console.log(cnt);
});
FIDDLE
You can use attribute-value selector
[id^=subchild]
will select all the elements whose id
value starts with(^
) child
.
Attribute value starts with selector.
Selects elements that have the specified attribute with a value beginning exactly with a given string.
Demo
$(function() {
var subchildrenLen = $('#parent [id^=subchild]').length;
$('body').append('No of children = ' + subchildrenLen);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="parent">
<div id="child1">
<div id="subchild1"></div>
</div>
<div id="child2">
<div id="subchild2"></div>
</div>
<div id="child3">
<div id="subchild3"></div>
</div>
</div>
You can also use querySelectorAll
with the same selector if you don't want to use jQuery.
var subchildrens = document.querySelectorAll('#parent [id^=subchild]').length;
If you want all the descendents count
var allChildrens = document.querySelectorAll('#parent div').length
alert($('#parent').find('div[id*="subchild"]').length)
DEMO
Attribute Contains Selector [name*=”value”]
DOCUMENTATION
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With