[javascript] How to get value of a div using javascript

This is my div:

<div id="demo" align="center"  value="1">
    <h3>By Color</h3>
    <input type="radio" name="group1" id="color1" value="#990000"  onClick="changeColor()"/><label for="color1">Red</label>
    <input type="radio" name="group1" id="color2" value="#009900" onClick="changeColor()"/><label for="color2">Green</label>
    <input type="radio" name="group1" id="color3" value="#FFFF00" onClick="changeColor()" /><label for="color3">Yellow</label><br><br><br>
</div>

I want the value attribute of that div (value="1").

I am trying like this:

function overlay()
{
    var cookieValue = document.getElementById("demo").value;    
    alert(cookieValue);
}

but it is showing "Undefined" how to get value 1 using javascript please suggest any solution,.

This question is related to javascript html

The answer is


You can try this:

var theValue = document.getElementById("demo").getAttribute("value");

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');

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"); 

Value is not a valid attribute of DIV

try this

var divElement = document.getElementById('demo');
alert( divElement .getAttribute('value'));

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