开发者

jquery select multiple <p> in <div>

开发者 https://www.devze.com 2023-02-15 12:52 出处:网络
HTML: <div id=\'example\'> <p> First paragraph</p> <p> Second paragraph</p>

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++)
{
   para开发者_如何学Pythongraph[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);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消