javascript 如何在javascript变量中获取div内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25947904/
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-10-28 05:17:14  来源:igfitidea点击:

How to get div content in javascript variable?

javascriptjqueryhtml

提问by satyam sharma

I am trying to get the content of a divin a JavaScript variable.

我试图div在 JavaScript 变量中获取 a 的内容。

I did try some code:

我确实尝试了一些代码:

<html>
     <head>
         <script>
             function data(){
                 alert();
                 var MyDiv1 = document.getElementById('newdata') 
                 alert(MyDiv1);
             }
         </script>
    </head>

    <body>
         <div id="newdata" style="background-color: red; width: 100px;height: 50px;">
             1 <!-- The content I'm trying to get -->
         </div>
         <a href="" onclick="data();">Logout</a>
    </body>
</html>

But it does not work correctly.

但它不能正常工作。

回答by Kartikeya Khosla

Instead of

代替

var MyDiv1 = document.getElementById('newdata')
alert(MyDiv1)

it should be

它应该是

var MyDiv1 = document.getElementById('newdata').innerHTML
alert(MyDiv1)

OR

或者

var MyDiv1 = document.getElementById('newdata')
alert(MyDiv1.innerHTML)

With .innerHTMLyou will get the htmlof specified elementin the DOM.

随着.innerHTML你会得到html指定elementDOM

EDIT:-

编辑:-

SEE DEMO HERE

在此处查看演示

回答by Arun Banik

You must use innerHTML.

您必须使用innerHTML

<html>
<head>
</head>
<body>
    <div id="newdata" style="background-color: red; width: 100px;height: 50px;">
        1
    </div>

    <a href="" onclick="data();">Logout</a>
</body>

    <script>
        function data() {
            var MyDiv1 = document.getElementById('newdata').innerHTML;
            alert(MyDiv1);
        }
    </script>

</html>