简体   繁体   English

可以在网页上的任何文字 <p> 标记或<span>标记是否以编程方式选择?</span>

[英]can any text on a webpage in a <p> tag or <span> tag be selected programmatically?

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? input元素和textarea元素可以很容易地做到这一点,但在其他情况下文本怎么样?

You can find an example of getting inner text from a <p> tag here . 您可以在此处找到从<p>标记获取内部文本的示例。 Same thing with a <span> . <span>

To set it you just need to assign the InnerText property. 要设置它,您只需要分配InnerText属性。

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. 如果你的javascript片段超出范围(在函数等中),请使用文档全局对象的GetElementById方法来检索<p><span>或其他任何内容 - 事实上,如果您指定了id,则可以使用任何元素执行此操作对元素。

JohnIdol's answer will work in all modern browsers except Firefox. JohnIdol的答案适用于除Firefox以外的所有现代浏览器。 See here for a browser compatibility chart on innerText . 有关innerText上的浏览器兼容性图表,请参见此处 As the link also shows, you can use textContent to get the same thing in FF. 如链接所示,您可以使用textContent在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. 使用getElementById的建议是一个很好的建议,但是请注意,如果元素的文本没有附加id,你仍然可以访问它的文本,这通常是<p><span>标签。 For example if you know the 4th <p> tag has the text you want you can do the following: 例如,如果您知道第4个<p>标记包含您想要的文本,则可以执行以下操作:

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

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

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