简体   繁体   English

jQuery在一组特定的p标签中获取文本

[英]JQuery get text within a specific set of p tags

I have a problem trying to obtain text between a certain set of <p> tags using JQuery - here is the html that I currently have: 我在尝试使用JQuery尝试在一组<p>标记之间获取文本时遇到问题-这是我目前拥有的html:

<div class="mainarea">
    <p>
        <strong>Location: </strong>
    </p>

    <!-- display search results -->
    <p>
        You searched for
        <strong>"xyz"</strong>.
    </p>

I'm trying to get the text within the second set of <p> tags (You searched for ...), but I keep getting the text from the first <p> tag (Location ...). 我正在尝试在第二组<p>标记(您搜索...)中获取文本,但是我一直从第一个<p>标记(位置...)获取文本。

So far I have this function: 到目前为止,我具有此功能:

$('.mainarea p') , which returns "Location..." and have tried to add the .text() function to it, but this doesn't seem to help. $('.mainarea p') ,它返回“ Location ...”并尝试向其添加.text()函数,但这似乎无济于事。

Use eq() or :eq selector 使用eq():eq选择器

$('.mainarea p').eq(1).text();

Using selector: 使用选择器:

$('.mainarea p:eq(1)').text();

Note: Used .text() as mentioned in the text. 注意:如文本中所述使用.text() To get innerHTML use .html() 要获取innerHTML,请使用.html()

 $('body').html($('.mainarea p').eq(1).html()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <div class="mainarea"> <p> <strong>Location: </strong> </p> <!-- display search results --> <p> You searched for <strong>"xyz"</strong>. </p> 

Similarly we can use the following code given bellow 类似地,我们可以使用以下给出的代码

console.log("value is"+$('.mainarea p:last').html()) ; 

Here your p position at last so i am using this approached.If p is not last element then we can use .eq()to set the index or get the index. 这是您最后的p位置,因此我正在使用此方法。如果p不是最后一个元素,则可以使用.eq()设置索引或获取索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM