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);
});
Related
I am currently trying to find the parent of a parent of an element. I have a link being clicked that is in a <td>, and I'd like to get the <tr> object.
Why wont "$(this).parent().parent()" work? What will?
Thanks,
Brendan
Edit: It appears an error in my syntax was throwing the whole thing off. "$(this).parent().parent()" does in fact work, but I wound up going with $(this).closest('tr')" because it seems like the most efficient solution.
The best way would probably be using closest:
$(this).closest('tr');
Check out the documentation:
Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.
It should work. You can also try $(this).parents(tag) , where tag is the tag you want to find.
For example:
$(this).parents("tr:first")
Will find the closest tr "up the chain".
That should work... you might try
$(this).parents(':eq(1)');
The .parents(selector) says get all ancestors that match the selector
and the :eq(1) says find the oneth (zero-indexed, so the second) element in the list
This snippet has performed for me in the past:
$(this).parent().parent();
Post some code for us to see if there might be another problem somewhere...
also try
$(this).closest('div.classname').hide();
If you have any sort of id/class for the parent, you can use parents() but that will give you all parents up to the < body > unless you filter() or stop it some other way like
$(this).parents('.myClass');
Hope this helps someone :)
Try wrapping the $(this).parent() into an jQuery object like $($(this).parent()) I often find the need to do this to make sure I have a valid jquery object. From there you should be able to get a hold of the parents parent, or using the prev() perhaps.
var getParentNode = function(elem, level) {
level = level || 1;
for (var i = 0; i < level; i++) {
if (elem != null) {
elem = elem.parentNode;
}
}
return elem;
}
.closest() is not always best option specially when you have same element construct.
<div>
<div>
<div>
</div>
</div>
</div>
You can do parent of a parent and it's very easy:
var parent = $('.myDiv').parent();
var parentParent = $(parent).parent();
var parentParentParent = $(parentParent).parent();
etc.
The accepted answer to this stackoverflow question is exactly what I need, but with one modification.
I need multiple .boxes. Not just one.
Each "box" has two divs that need to be faded between.
From this snippet of the code:
$(document).ready(function () {
var allBoxes = $("span.boxes").children("span");
transitionBox(null, allBoxes.first());
});
I understand that I should maybe first, put all the .boxes into an array and then loop over that to get each of their children span elements.
But I'm not entirely sure that this is (a) the best practice, (b) correct, and (c) if there is just a better way in the first place.
Do you mean something like this http://jsfiddle.net/8odoros/CYJLA/306/ ?
Using
$( "div.boxes" ).each(function( index ) {
var allBoxes = $(this).children("div");
transitionBox(null, allBoxes.first());
});
applies the same effect to all .boxes
JS:
this.par = $(this).find("p");
HTML:
<p></p>
The problem is that I dont want to find p tag, but rather a div with a specific ID like this one below.
<div id="abc"></div>
Use the ID selector:
var myDivObj = $("#abc");
Take a look at the list of jQuery selectors.
Additional Information:
It's difficult to tell by your code what you're trying to do, but based on what you've posted, there is no reason to use $(this). The ID selector alone should meet your needs.
Well, you can just use the id selector:
$(this).find('#abc');
Since ids should be unique on the page, you may as well just use it as the constructor:
$('#abc');
If this isn't exactly the same, you're doing something wrong.
this.par = $(this).find("#abc");
You don't want to do that. Don't add properties to the html elements. This is better:
var par = $(this).find('#idOfElement')
Storing the result in this.par is a very bad idea, since this refers to a DomElement.
What you might be looking for is jQuery .data():
$(this).data('par', $(this).find('#idOfElement'))
Which allows you to associate #idOfElement with this.
use id selector
this.par = $(this).find("#abc");
but id is uniqe you can remove $(this).find and use this code
this.par = $("#abc");
I am currently trying to find the parent of a parent of an element. I have a link being clicked that is in a <td>, and I'd like to get the <tr> object.
Why wont "$(this).parent().parent()" work? What will?
Thanks,
Brendan
Edit: It appears an error in my syntax was throwing the whole thing off. "$(this).parent().parent()" does in fact work, but I wound up going with $(this).closest('tr')" because it seems like the most efficient solution.
The best way would probably be using closest:
$(this).closest('tr');
Check out the documentation:
Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.
It should work. You can also try $(this).parents(tag) , where tag is the tag you want to find.
For example:
$(this).parents("tr:first")
Will find the closest tr "up the chain".
That should work... you might try
$(this).parents(':eq(1)');
The .parents(selector) says get all ancestors that match the selector
and the :eq(1) says find the oneth (zero-indexed, so the second) element in the list
This snippet has performed for me in the past:
$(this).parent().parent();
Post some code for us to see if there might be another problem somewhere...
also try
$(this).closest('div.classname').hide();
If you have any sort of id/class for the parent, you can use parents() but that will give you all parents up to the < body > unless you filter() or stop it some other way like
$(this).parents('.myClass');
Hope this helps someone :)
Try wrapping the $(this).parent() into an jQuery object like $($(this).parent()) I often find the need to do this to make sure I have a valid jquery object. From there you should be able to get a hold of the parents parent, or using the prev() perhaps.
var getParentNode = function(elem, level) {
level = level || 1;
for (var i = 0; i < level; i++) {
if (elem != null) {
elem = elem.parentNode;
}
}
return elem;
}
.closest() is not always best option specially when you have same element construct.
<div>
<div>
<div>
</div>
</div>
</div>
You can do parent of a parent and it's very easy:
var parent = $('.myDiv').parent();
var parentParent = $(parent).parent();
var parentParentParent = $(parentParent).parent();
etc.
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