最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to get div content in javascript variable? - Stack Overflow

programmeradmin0浏览0评论

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

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.

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

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.

Share Improve this question edited Sep 20, 2014 at 11:42 drage0 3723 silver badges8 bronze badges asked Sep 20, 2014 at 10:42 satyam sharmasatyam sharma 551 gold badge4 silver badges10 bronze badges 1
  • var content = MyDiv1.innerHTML; – Sirko Commented Sep 20, 2014 at 10:43
Add a ment  | 

2 Answers 2

Reset to default 4

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 .innerHTML you will get the html of specified element in the DOM.

EDIT:-

SEE DEMO HERE

You must use 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>
发布评论

评论列表(0)

  1. 暂无评论