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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:20:38  来源:igfitidea点击:

Selecting <p> within a div using jQuery

javascriptjquery

提问by Mossawir Ahmed

I want to select the second <p>tag and style it within a itemizeclass 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 > divgoes 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 pthat 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/

在这里试试: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..

希望它会起作用..

回答by jakee

$('.itemize>div>p').first().css(styles go here)most of the ones above work as well

$('.itemize>div>p').first().css(styles go here)上面的大多数也可以工作

jQuery selectors work a bit like css selectors, check out this tutorialto get more info.

jQuery 选择器的工作方式有点像 css 选择器,请查看本教程以获取更多信息。