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');
Returns an array of HTMLParagraphElement objects. However, I want to return jQuery objects. (So ββthat I can use, for example:
for(i=0;i<paragraphs.length;i++) { paragraph[i].hide(); } Is there a way I can do this easily? Thank you
Thanks to everyone for input. An iteration of the div p array was necessary (sorry if that was unclear), so $('div#example p').hide(); was not the right decision. 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 :)
Example:
$('#examples p').hide(); div is not required
You can still use the selector request you are using. i.e:
var paragraphs = $('div#examples p'); paragraphs.hide(); or
$('div#examples p').hide(); This is the most efficient way to query dom for the current problem:
$('#examples).find('p').hide();
These are just a few keystrokes, but the selection is much faster than the examples given here by others. The reason is that it first traverses all the divs, and then finds those that can have the given identifier, and then traverses them to find the corresponding p tags.
In my solution, it finds only #examples , and then jumps to its p tag.
try it...
$('div#examples p').hide(); From the point of view of your question, the answer will be, as others have stated:
$('div#examples p').hide(); But for the case where you have to iterate over every object 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 hiding, then just use the first example. The second example is when an application function is specific to each object. The following example doubles the height of all returned objects, which could not be done in the same way as in the first example:
$('div#examples p').each(function(){ var h = $(this).height(); $(this).height(h * 2); });