How to get value of a div using javascript
Solution 1:
DIV
s do not have a value
property.
Technically, according to the DTDs, they shouldn't have a value
attribute either, but generally you'll want to use .getAttribute()
in this case:
function overlay()
{
var cookieValue = document.getElementById('demo').getAttribute('value');
alert(cookieValue);
}
Solution 2:
To put it short 'value' is not an valid attribute of div. So it's absolutely correct to return undefined.
What you could do was something in the line of using one of the HTML5 attributes 'data-*'
<div id="demo" align="center" data-value="1">
And the script would be:
var val = document.getElementById('demo').getAttribute('data-value');
This should work in most modern browsers
Just remember to put your doctype as <!DOCTYPE html>
to get it valid
Solution 3:
As I said in the comments, a <div>
element does not have a value
attribute. Although (very) bad, it can be accessed as:
console.log(document.getElementById('demo').getAttribute);
I suggest using HTML5 data-*
attributes rather. Something like this:
<div id="demo" data-myValue="1">...</div>
in which case you could access it using:
element.getAttribute('data-myValue');
//Or using jQuery:
$('#demo').data('myValue');
Solution 4:
First of all
<div id="demo" align="center" value="1"></div>
that is not valid HTML. Read up on custom data attributes or use the following instead:
<div id="demo" align="center" data-value="1"></div>
Since "data-value" is an attribute, you have to use the getAttribute function to retrieve its value.
var cookieValue = document.getElementById("demo").getAttribute("data-value");