有选择地从<div> </div>获取文本

时间:2012-02-16 00:02:49

标签: javascript jquery

<div class="myDiv">
    <p>I need get<strong>this</strong>
        <a title="And this" href="#">but not this</a>
    </p>
    <p>And also<strong>This</strong>
        <a title="And this" href="#">but not this</a>
    </p>
</div>

除了嵌套标签中的文本外,我如何抓取p标签中的所有内容。而且我还需要为标签a获得“title”attirbute的值?

3 个答案:

答案 0 :(得分:2)

使用http://api.jquery.com/replaceWith/

  • 创建克隆
  • 用标题属性替换a标签
  • 在克隆节点上调用text()

http://jsfiddle.net/mendesjuan/cBejv/2/

var clone = $('.myDiv p').clone();
clone.find('a').replaceWith(function() {
   return this.getAttribute('title');
})
console.log(clone.text());

输出

I need get this

 And this And also This

 And this 

答案 1 :(得分:1)

这样的事情会起作用。可能有更好的方法来做到这一点,但这是首先想到的。

var $clone = $('.myDiv').clone();

$clone.find('a').remove();

$('#output').append($clone.text());​

确保添加id="output"元素以查看结果。

答案 2 :(得分:1)

这个怎么样:

$('.myDiv a').text('');
$('.myDiv p').each(function() {
    console.log($(this).text()+$('a',this).attr('title'));
});

jsFiddle 示例。