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;
Related
Here is a minimal version of my problem, given:
<div class="foo">
<div class="a"> </div>
<div class="b"> </div>
<div class="c"> </div>
</div>
I want to insert the element <div class="bar">WORKS!</div> into one of the children randomly.
var kids = $(.foo).children();
var idx = Math.floor(Math.random() * kids.length);
var target = kids[idx];
I think this is a misunderstanding between how javascript and jQuery work together. I'm learning both at the moment, so here is my due diligence in solving the problem:
target.append(...) fails since target is not a JQuery object and .append() is a JQuery call.
$(target).append(...) does strange things, copying items around in the DOM and I don't understand why. It may work in this isolated example, but it's causing crazy town with many foo's, a's, b's and c's.
target.innerHTML=... doesn't seem to work and I don't want to erase any previous content with the append.
Try,
var target = kids.eq(idx);
instead of,
var target = kids[idx];
Please read here to know more about .eq()
Try .eq()
var target = kids.eq(idx);
I want to remove some silblings. I tried as given below.
But not working. why? And how to solve it?
<div>
<div id="idx1">child1 </div>
<div id="idx2">child2</div>
<div id="idx3">child3</div>
...
<div id="/a/b/c">This should be last child</div>
<div id="idx4">Remove it.</div>
<div id="idx5">Remove it.</div>
<div id="idx6">Remove it.</div>
...
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
// Since the id contains special chars,
// javascript method has been used to get the element.
lastChildObj = jQuery(document.getElementById('a/b/c'));
// I don't know how to remove the childs after lastChildObj.
// I tried as given below.
lastChildObj.filter('~').remove();
There are two key steps to this.
Select the elements to remove
Remove them
Step 1 can be broken down into two parts, obtaining a reference to the last element to keep, then getting a list of all of its siblings that come after it. Step 2 just uses the .remove() function.
$(document.getElementById('/a/b/c')).nextAll().remove();
You can still use jquery for your selector but you need to escape the id like so :
$("#\\/a\\/b\\/c")
Then you just need to select any following divs like this :
$("#\\/a\\/b\\/c").nextAll().remove();
http://jsfiddle.net/8mMJq/
Further informations about special characters in selectors : http://api.jquery.com/category/selectors/
This should work for you:
var base = document.getElementById('/a/b/c');
while(base.nextSibling){ // While the element has siblings
base.parentElement.removeChild(base.nextSibling); // remove the siblings from the parent element.
}
Working example
You can also make it slightly more efficient:
var base = document.getElementById('/a/b/c');
while(base.parentElement.removeChild(base.nextSibling)) // Remove the nextSiblings while they exist.
Example
Try this :
$("#\\/a\\/b\\/c").nextAll().remove();
JsFiddle : http://jsfiddle.net/QcvWQ/
First of all change id from "/a/b/c" to ie "abc" and then run following
$("#abc").nextAll().each(function () { $(this).remove());});
So I have a div with some child elements and when I select one with jQuery I want to get the index of it within a selector
<div>
<div class="red"></div>
<div class="red"></div>
<div class="red"></div>
<div class="blue"></div>
<div class="red"></div>
<div class="blue"></div>
<div class="blue"></div>
<div class="red"></div>
</div>
So lets say that I have the last element in the main div selected. If I call index() on it it will give me '7' because out of all the child elements the index is '7'. But now lets say I want to get the index based on the other 'red' elements, the goal is to return a value of '4' because out of all of the 'red' elements it is the fifth one. I looked through the documentation and didnt find a whole lot, then I experimented with putting selectors in the index() method like index('.red') but I couldn't get anything working.
Well, the documentation says:
.index( element )
element The DOM element or first element within the jQuery object to look for.
So can do:
selectedElements.filter('.red').index(this);
If you don't have selectedElements already, you can select corresponding siblings with, for example:
$(this).parent().children('.red')
If every element has only one class and then the filter can be dynamic:
var index = $(this).parent().children('.' + this.className).index(this);
Use the .index() function documented here
For the above if one wants to get the index of a element of the red class use $('div .red').index(elem);
$('div .red) will create a list of the elements with the red class within the div. .index(elem) will search for the elem within the array.
Running through all of them using id=test as parent
DEMO : http://jsfiddle.net/T7fXR/
$('#test > div').each(function(){
var thisClass=$(this).attr('class');
$(this).css('background',thisClass );
/* get index based on class*/
var idx=$('.'+thisClass).index(this);
$(this).text('Index= '+idx)
})
For me, this works just fine with your given HTML:
$('div').eq(5).index('.red') // 3
You can place selectors into the .index() function.
I need to use jQuery to locate all DIV tags that have no attributes on them and apply a class to each. Here's a sample HTML:
<div id="sidebar">
<div>Some text goes here</div>
<div class="something">something goes here</div>
<div>Another div with no attributes.</div>
</div>
So, I need to take that and turn it into this:
<div id="sidebar">
<div class="myClass">Some text goes here</div>
<div class="something">something goes here</div>
<div class="myClass">Another div with no attributes.</div>
</div>
How do you locate elements of type div that have no attributes via jQuery? Thanks.
Here you go:
$('div', '#sidebar').filter(function () {
return this.attributes.length === 0;
})
Live demo: http://jsfiddle.net/phbU9/
The attributes property returns a list of all attributes set on the element. "Naked" elements have an empty attributes list.
Update: Be sure to read Tim's answer below which provides a solution for older versions of IE, since my own solution doesn't work in IE8 and below.
#Šime's answer is close but doesn't work in IE 6, 7 or 8, where an element's attributes collection has an entry for every possible attribute, not just those specified in the HTML. You can get round this by checking each attribute object's specified property.
Live demo: http://jsfiddle.net/timdown/6MqmK/1/
Code:
$("div").filter(function() {
var attrs = this.attributes, attrCount = attrs.length;
if (attrCount == 0) {
return true;
} else {
for (var i = 0; i < attrCount; ++i) {
if (attrs[i].specified) {
return false;
}
}
return true;
}
});
check this out:
http://jsfiddle.net/thilakar/CHux9/
You need to give some sort of selector, in this case Ive used your side bar but it can be anything. Then get the children that have no class attribute and add a new class. See JSFiddle for the example:
http://jsfiddle.net/HenryGarle/q3x5W/
$("#sidebar").children('div:not([class])').addClass('newClass');
So this would return the 2 elements with no class tag and leave the sidebar and div with the class completely unaffected.
You could use a combination of jQuery's has attribute selector and the not selector. For example:
$('div:not([class], [id])').addClass('myClass');
jsFiddle demonstrating this
With this approach, you need to explicitly specify the attributes to check the presence of. Sime's solution would apply the class to divs that do not have any attributes at all.
To expound upon Tim Down's answer, I recommend checking that the attrs var not null special cases where the html has comment tags, etc.
try $('div:not([class])').addClass('myClass');
it is a general approach because the class will apply to all the div that have no class
$('#sidebar div')` or more general `$('div'); //returns collections of divs
to answer the question:
$('#sidebar div').addClass('myClass');
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