获取文本元素 [英] Get Text Element

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

问题描述

我是初学者.我正在尝试弹出一个带有< div> 文本内容的警报框,但是却显示 null .

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

Javascript:

Javascript:

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

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 >

我在做什么错了?

推荐答案

尝试:

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

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

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.

在这里解释: http://www.quirksmode.org/dom/intro.html

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

If the text is the only child innerHTML will work fine

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

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

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

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

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

这篇关于获取文本元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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