中的网页上的任何文本都可以吗? 标签或 以编程方式选择标签?

发布于 2024-07-21 00:46:38 字数 88 浏览 3 评论 0原文

网页上标签或标记中的任何文本

是否可以通过编程方式选择 ? input 元素和 textarea 元素可以轻松做到这一点,但在其他情况下文本怎么样?

can any text on a webpage in a

tag or tag be selected programmatically? the input element and textarea element can do that easily, but how about text in other cases?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ゞ花落谁相伴 2024-07-28 00:46:38

您可以找到从

标记获取内部文本的示例 此处。 与 相同。

要设置它,您只需分配 InnerText 属性。

如果您的 javascript 代码段超出范围(在函数等中),请使用 GetElementById 方法文档全局对象的属性来检索您的

或其他任何内容 - 事实上,您可以使用任何元素执行此操作,前提是您为该元素分配了 id元素。

You can find an example of getting inner text from a <p> tag here. Same thing with a <span>.

To set it you just need to assign the InnerText property.

If your javascript snippet is out of scope (in a function etc) use the GetElementById method of the document global object to retrieve your <p> or <span> or whatever - in fact you can do this with any element provided you assign an id to the element.

粉红×色少女 2024-07-28 00:46:38

JohnIdol 的答案适用于除 Firefox 之外的所有现代浏览器。 有关 innerText 上的浏览​​器兼容性图表,请参阅此处 。 正如链接所示,您可以使用 textContent 在 FF 中获得相同的内容。

使用 getElementById 的建议是一个很好的建议,但值得注意的是,如果元素没有附加 id,您仍然可以访问该元素的文本,这种情况通常是

标签。 例如,如果您知道第四个

标记包含您想要的文本,您可以执行以下操作:

var p = document.getElementsByTagName('p')[3];
var text = p.innerText || p.textContent;

JohnIdol's answer will work in all modern browsers except Firefox. See here for a browser compatibility chart on innerText. As the link also shows, you can use textContent to get the same thing in FF.

The suggestion to use getElementById is an excellent one, but it's good to note that you can still access the text of an element if it doesn't have an id attached to it, which is frequently the case with <p> and <span> tags. For example if you know the 4th <p> tag has the text you want you can do the following:

var p = document.getElementsByTagName('p')[3];
var text = p.innerText || p.textContent;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文