Count immediate child div elements using jQuery - javascript

I have the following HTML node structure:
<div id="foo">
<div id="bar"></div>
<div id="baz">
<div id="biz"></div>
</div>
<span></span>
</div>
How do I count the number of immediate children of foo, that are of type div? In the example above, the result should be two (bar and baz).

$("#foo > div").length
Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.

I recommend using $('#foo').children().size() for better performance.
I've created a jsperf test to see the speed difference and the children() method beaten the child selector (#foo > div) approach by at least 60% in Chrome (canary build v15) 20-30% in Firefox (v4).
By the way, needless to say, these two approaches produce same results (in this case, 1000).
[Update] I've updated the test to include the size() vs length test, and they doesn't make much difference (result: length usage is slightly faster (2%) than size())
[Update] Due to the incorrect markup seen in the OP (before 'markup validated' update by me), both $("#foo > div").length & $('#foo').children().length resulted the same (jsfiddle). But for correct answer to get ONLY 'div' children, one SHOULD use child selector for correct & better performance

$("#foo > div")
selects all divs that are immediate descendants of #foo
once you have the set of children you can either use the size function:
$("#foo > div").size()
or you can use
$("#foo > div").length
Both will return you the same result

$('#foo').children('div').length

In response to mrCoders answer using jsperf why not just use the dom node ?
var $foo = $('#foo');
var count = $foo[0].childElementCount
You can try the test here: http://jsperf.com/jquery-child-ele-size/7
This method gets 46,095 op/s while the other methods at best 2000 op/s

$('#foo > div').size()

$("#foo > div").length
jQuery has a .size() function which will return the number of times that an element appears but, as specified in the jQuery documentation, it is slower and returns the same value as the .length property so it is best to simply use the .length property.
From here: http://www.electrictoolbox.com/get-total-number-matched-elements-jquery/

var divss = 0;
$(function(){
$("#foo div").each(function(){
divss++;
});
console.log(divss);
});
<div id="foo">
<div id="bar" class="1"></div>
<div id="baz" class="1"></div>
<div id="bam" class="1"></div>
</div>

With the most recent version of jquery, you can use $("#superpics div").children().length.

var n_numTabs = $("#superpics div").size();
or
var n_numTabs = $("#superpics div").length;
As was already said, both return the same result.
But the size() function is more jQuery "P.C".
I had a similar problem with my page.
For now on, just omit the > and it should work fine.

$("div", "#superpics").size();

Try this for immediate child elements of type div
$("#foo > div")[0].children.length

Related

JQuery how to find the closest element that is neither a parent nor a child of the current element?

Say I have HTML that looks like this:
<div>
<div>
<div class="calendar start">
</div>
</div>
<div>
<div class="calendar end">
</div>
</div>
</div>
We can assume that the start and end will always be on the same "level" of a branch from each other, and will at some point share a common parent.
Without knowledge of the exact HTML structure, how would I find calendar end from calendar start? What if they are nested further down?
Edit: For clarification. I want to start at start's parent. Search all child elements for end. Then move to the next parent, and search all child elements...etc till I find end. I am wondering if this is possible with built in JQuery functions, without writing my own DOM traversal logic.
You can do it like below, But it is a costlier process.
var parentWhichHasCalEnd =
$($(".calendar.start").parents()
.get().find(itm => $(itm).find(".calendar.end").length));
var calEnd = $(".calendar.end", parentWhichHasCalEnd);
DEMO
Explanation: We are selecting the .start element first, then we are retrieving its parent elements. After that we are converting that jquery object collection to an array of elements by using .get(). So that we could use .find(), an array function over it. Now inside of the callBack of find we are checking for .end over each parent element of .start, if a parent has .end then we would return that parent. Thats all.
You could get more understanding, if you read .get(), .find(), and arrow functions.
You can use jQuery#next() method from .start parent element
var startSelector = $('body > div > div:nth-child(3) > .start')
var endSelector = secondStart.parent().next().find('.end');
I think this method is faster rather than jQuery#children() method, but you can benchmark it if you want to
btw you may check my answer based on this JSBin
i don't know if i got this right but have you tried children function in jquery
$( ".calender" ).children( ".end" )
and for the parent you can use parent() function so you can first check the parent then the children or vicversa
edit:
if you dont know the exact structure the better way is to find the common parent and then search it's children :
$( ".calender.start").closest('.common-parent').children('.calender.end');
closest function give the nearest parent
Try:
$('.start').parent().parent().find('.end');

Best performance to select first 0 - n children of a parent in jQuery and javascript

I want to select the first n children under a specific parent. For this case I don't want to use each index unless its the best performance.
Example:
// select first 20 child elements
var twentyChildElements = $("div").children("span(20)");
<div>
<span index="1"/>
<span index="2"/>
<span index="3"/>
....
<span index="n"/>
</div>
You can use the :lt pseudo-selector:
var twentyChildElements = $("div > span:lt(20)");
> means immediate children, and :lt(2) means the first 20 elements that match the selector (it's zero-based, so this returns elements 0 through 19).
Just use jQuery's slice:
var twentyChildElements = $("div").children("span").slice(0, 20);
See also this performance test case - it's always faster than :lt(n), but can be outperformed by native selector engines.
Go fancy... Let css do the job! ;)
Use a negative nth-child combinator selector. MDN nth-child selector
var twentyChildElements = $("div > span:nth-child(-n+20)");
You can use :lt approach:
$("div").children("span:lt(n)")

Find the number of div elements under a parent div

Is there a jquery method that allows you to find the number of div elements under a parent node.
So say I have this set up
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
</div>
If I want to find the number of divs under parent it would be 2
or this
<div id="parent">
<div id="child1"><div id="childer1"></div></div>
<div id="child2"></div>
</div>
It should give me 3.
Is there any method that does that for you?
Yes. If you want all of them:
var divs = $('#parent').find('div').length;
or
var divs = $('#parent div').length;
If you just want the immediate children:
var divs = $('#parent').children('div').length;
or
var divs = $('#parent > div').length;
The variations involving "find" and "children" are handy in case your starting element is something for which you've already got a reference.
This should do it:
var descendant_count = $("#parent div").length;
Pure vanilla solution:
document.getElementById('parent').querySelectorAll('div').length;
jsFiddle here.
To note: querySelectorAll() is only supported in more recent versions of IE (as of IE8+).
Without a library
document.getElementById("parent_div").children.length;
You can get number using length
$('#parent div').length
Try:
$('#parent').find('div').length;

Jquery - Accessing nested child elements

Assume I have the following HTML -
<DIV id="ParentDiv">
<DIV id="SubDiv1"></DIV>
<DIV id="SubDiv2">
<INPUT id="input">
</DIV>
</DIV>
To access the input element using jquery, it would be simply $("#input"). What I'm trying to do is access it, assuming I only know the ID of the top level div.
Currently I have
$($($("#ParentDiv").children()[1]).children()[0])
Which does seem to work. Is there a cleaner way of writing this, or is the way I am doing it ok?
You would just perform a .find() implicitly or explicitly:
$('#ParentDiv input'); // implicitly
$('#ParentDiv').find('input'); // explicitly
Reference: .find()
You can try:
1. $('#ParentDiv input')
2. $('input', '#ParentDiv')
3. $('#ParentDiv').find('input')
if you need to find the input from SubDiv2 only upon having parentDiv information you can use
$("#ParentDiv div:eq(1) input")
or
$("#ParentDiv div:eq(1)").find("input")
Where eq(1) will get you with the second div inside ParentDiv
Try this:
$('#ParentDiv').find('input');
Many ways to do it. Here is one
$("#ParentDiv > div:eq(1) > input")
how about
$("#ParentDiv :input")
try this
jQuery('#input').val();

jquery select multiple <p> in <div>

HTML:
<div id='example'>
<p> First paragraph</p>
<p> Second paragraph</p>
<p> Third paragraph</p>
</div>
Javascript with JQuery:
var paragraphs = $('div#examples p');
This returns an array of HTMLParagraphElement objects. However, I wish to return Jquery objects. (So that I can use e.g:
for(i=0;i<paragraphs.length;i++)
{
paragraph[i].hide();
}
Is there a way I can easily do this? Thanks.
example:
$('#examples p').hide();
div is not necessary
This the the most performant way to query the dom for present issue:
$('#examples).find('p').hide();
It's a few more keystrokes, but the selection happens so much faster than the examples given here by others. The reason being is that it traverses all divs first, then finds those that may have the given id, then traverses to find their matching p tags.
In my solution it finds just #examples and then traverses down to its p tag.
You can still use the the selector query you use. i.e:
var paragraphs = $('div#examples p');
paragraphs.hide();
or
$('div#examples p').hide();
Thanks everybody for input. Iteration of the div p array was necessary (sorry if that wasn't clear), so doing $('div#example p').hide(); was not a proper solution. I ended up doing the following:
var arr = $('div#example p');
for(i=0;i<arr.length;i++)
{
$(arr[i]).hide();
}
Hope this is useful for people in the future:)
try this...
$('div#examples p').hide();
From the looks of your question the answer would be, as stated by others:
$('div#examples p').hide();
But for the case that you have to iterate through each object that is returned from a jQuery query you should use this syntax:
$('div#examples p').each(function(){
$(this).hide();
});
But remember, if it's as simple as hide, then just use the first example. The second example is when the applied function is specific to each object. The next example is doubling the heights of all returned objects, which could not be done in the same way that the first example is:
$('div#examples p').each(function(){
var h = $(this).height();
$(this).height(h * 2);
});

Categories