Javascript 获取文本元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5444234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:13:08  来源:igfitidea点击:

Get Text Element

javascript

提问by Mansour

I am a beginner. I am trying to pop up an alert box with the text contents of a <div>, but am getting null.

我是初学者。我试图用 a 的文本内容弹出一个警告框<div>,但我得到null.

Javascript:

Javascript:

alert(document.getElementById("ticker").value);

HTML

HTML

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <script src="Tick.js" type="text/javascript"></script>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
            <div   id="ticker">
               Sample
            </div>
</asp:Content >

What am I doing wrong?

我究竟做错了什么?

回答by Miquel

Try:

尝试:

alert(document.getElementById("ticker").innerHTML);

Bear in mind however that the text inside a node is considered a child of that node, innerHTML will return all the HTML within that element.

但是请记住,节点内的文本被视为该节点的子节点,innerHTML 将返回该元素内的所有 HTML。

It is explained here: http://www.quirksmode.org/dom/intro.html

解释如下:http: //www.quirksmode.org/dom/intro.html

If the text is the only child innerHTML will work fine

如果文本是唯一的子元素,innerHTML 可以正常工作

The following code is equivalent to use innerHTML for your sample:

以下代码等效于对您的示例使用 innerHTML:

alert(document.getElementById("ticker").firstChild.nodeValue);

it retrieves the value of the node of the first child of your div

它检索您的 div 的第一个子节点的节点的值

回答by dekiss

innerHTML will give you all content that is inside the element including the HTML elements all all other nodes and text in them. If you want to get only the text that is directly in the element use nodeValue or text Content:

innerHTML 将为您提供元素内的所有内容,包括 HTML 元素所有其他节点和其中的文本。如果您只想获取直接在元素中的文本,请使用 nodeValue 或文本内容:

like this: text

像这样:文本

var a = document.getElementById("id").childNodes[0].nodeValue;
var b = document.getElementById("id").childNodes[0].textContent;

This will get the text - "abc" and put it into variables a and b, they both will have "abc". Be careful with textContent however because textContent is not supported in Internet Explorer 8, nodeValue on other hand is in DOM1 which means very old browsers support it. And also if you are beginner maybe you don't know, but if you are executing javascript code right after browser open web page, then you have to link the javascript files on the bottom of your html code right before body closing tag, this is because if you try to get/set text for example for one element and if that element is not yet loaded by the browser you will get javascript error and your code will not function. This will happen if you link your javascript files or put your javascript code in the head of the page. Browsers read the page from top to bottom and as they read it they execute everything and place in the computer memory - RAM, this is called parsing. So if you put the javascript code before the content of the page is loaded, and if the javascript code tries to read or set some element that is not yet read by the browser you will get error.

这将获得文本 - “abc”并将其放入变量 a 和 b 中,它们都将具有“abc”。但是要小心 textContent,因为 Internet Explorer 8 不支持 textContent,另一方面,nodeValue 在 DOM1 中,这意味着非常旧的浏览器支持它。而且,如果您是初学者,也许您不知道,但是如果您在浏览器打开网页后立即执行 javascript 代码,那么您必须在正文结束标记之前链接 html 代码底部的 javascript 文件,这是因为如果您尝试为一个元素获取/设置文本,并且如果该元素尚未被浏览器加载,您将收到 javascript 错误并且您的代码将无法运行。如果您链接您的 javascript 文件或将您的 javascript 代码放在页面的头部,就会发生这种情况。浏览器从上到下读取页面,并在读取页面时执行所有内容并将其放入计算机内存 - RAM,这称为解析。因此,如果您在加载页面内容之前放置 javascript 代码,并且如果 javascript 代码尝试读取或设置浏览器尚未读取的某些元素,您将收到错误消息。

回答by Jon Gauthier

Use innerHTML.

使用innerHTML.

alert(document.getElementById('ticker').innerHTML);

Or even better, use jQuery's text():

或者更好的是,使用 jQuery 的text()

alert($('#ticker').text());

回答by moe

alert(document.getElementById("ticker").innerHTML);

回答by Shadow Wizard is Ear For You

It won't be available until the document is loaded. Change the JS code to:

在加载文档之前它将不可用。将JS代码修改为:

window.onload = function() {
   alert(document.getElementById("ticker").innerHTML);
}

回答by Qasim

The problem with textContent is, it gives you the nested text inside other HTML elements too.

textContent 的问题在于,它也为您提供了其他 HTML 元素中的嵌套文本。

So I ended up getting the entire content as a string, and then got what I needed using substrings:

所以我最终将整个内容作为一个字符串,然后使用子字符串获得了我需要的内容:

var contentString = "<h3>Jimmy John</h3> some text content that I need to get <span>...",
    startIndex = contentString.indexOf('</h3>') + 5; //indexOf gives index of '<', so incrementing
    endIndex = contentString.indexOf('<span>'),
    length = endIndex = startIndex;

var myText = contentString.substr(startIndex, length); //Voila