1

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.

1
  • var content = MyDiv1.innerHTML; Commented Sep 20, 2014 at 10:43

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

how can i change color of div if value is 1 and if value is 2 then remain same
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.