Javascript 使用 jQuery 在 div 中选择 <p>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11077977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting <p> within a div using jQuery
提问by Mossawir Ahmed
I want to select the second <p>
tag and style it within a itemize
class div. Here is the example HTML:
我想选择第二个<p>
标签并在itemize
类 div 中设置它的样式。这是示例 HTML:
<div class="itemize">
<p> Order Summery</p>
<div>
<p><strong>Packages:</strong> </p> <!-- i want to select this P tag-->
<p><strong>Date:</strong> </p>
<p><strong>Style:</strong> </p>
</div>
</div>
I want to select and style the first <p>
which is immediately after the second <div>
. The second <p>
has no ID or class.
我想选择和设计第一个<p>
紧跟在第二个之后的样式<div>
。第二个<p>
没有 ID 或类。
How can I select it via jQuery?
如何通过 jQuery 选择它?
采纳答案by Sarfraz
You can do this way:
你可以这样做:
$('.itemize > div > p:eq(0)')
.itemize > div
goes till:
.itemize > div
一直到:
<div class="itemize">
<p> Order Summery</p>
</div>
And
和
.itemize > div > p:eq(0)
.itemize > div > p:eq(0)
<div class="itemize">
<p> Order Summery</p>
<div>
<p><strong>Packages:</strong> </p>
</div>
</div>
The >
allows to target direct children whereas eq(index)
is used to get first p
that you want.
在>
允许而目标直接儿童eq(index)
用于获取第一p
是你想要的。
回答by VibhaJ
$('.itemize div p:first').html()
Check this link: http://jsfiddle.net/QJTYx/
检查此链接:http: //jsfiddle.net/QJTYx/
If you want to add class to that p tag:
如果要将类添加到该 p 标签:
$('.itemize div p:first').addClass('selected');
回答by Arvind Bhardwaj
var test = $('.itemize')?.find('div:first')?.find(?'p:first')???.html();
alert(test);
?
Try here: http://jsfiddle.net/arvind07/H8vwA/
回答by ma?ek
This should do the trick
这应该可以解决问题
$('.itemize div p').first().addClass('hello');
回答by abuduba
$('.itemize>div>p:first').addClass('someClass');
回答by Wahid4sap
You can try this..
你可以试试这个..
$(".itemize div p:first").text();
hope it will works..
希望它会起作用..