如何只抓取div中的第一段文本? [英] How to just grab the first block of text in a div?

查看:62
本文介绍了如何只抓取div中的第一段文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取链接的文本-<a href></a>之间的内容.

I'm trying to just grab a link's text — the stuff between <a href> and </a>.

var title = $(uCW).find('[href^="https://l.facebook"]').text();
console.log(title);

现在,我的代码正在从多个链接中获取文本(有多个 https://l.facebook 链接在div中)并将其合并.有什么方法可以只从第一个链接中获取文本吗?我已经尝试过

Right now, my code is grabbing text from multiple links (there are multiple https://l.facebook links in the div) and combining them. Is there any way to just grab the text from the first link? I've tried

var title = $(uCW).find('[href^="https://l.facebook"]').text()[0];
console.log(title);

但是我只是得到一个错误:添加按钮时发生错误.TypeError:$(...).find(...)[0] .text不是函数."

But I just get an error: "Error occurred when adding button. TypeError: $(...).find(...)[0].text is not a function."

推荐答案

尝试

var title = $(uCW).find('[href^="https://l.facebook"]:first').text();

这会将您的搜索限制为第一个匹配的元素.

This will limit your search to the first matching element.

仅了解到:first在当前的jQuery版本中已弃用. https://api.jquery.com/first-selector/.

Just learned that :first is deprecated in the current jQuery version. https://api.jquery.com/first-selector/ .

因此,将其替换为.first():

var title = $(uCW).find('[href^="https://l.facebook"]').first().text();

这篇关于如何只抓取div中的第一段文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆