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
2 Answers
Reset to default 4Instead 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>