How to get div value 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 need the value attribute of this div (value = "1").
I try like this:
function overlay() { var cookieValue = document.getElementById("demo").value; alert(cookieValue); } but it shows "Undefined" how to get the value 1 using javascript, suggest any solution,
DIV do not have a value property.
Technically, according to the DTD, they should not have a value attribute, but usually you want to use .getAttribute() in this case:
function overlay() { var cookieValue = document.getElementById('demo').getAttribute('value'); alert(cookieValue); } In short, the value is not a valid div attribute. Therefore, it is absolutely correct to return undefined.
What you could do is something in the use string of one of these HTML5 attributes - * '
<div id="demo" align="center" data-value="1"> And the script will be:
var val = document.getElementById('demo').getAttribute('data-value'); This should work in most modern browsers. Remember to put your doctype as <!DOCTYPE html> so that it is valid
As I said in the comments, the <div> element does not have a value attribute. Although (very) bad, it can be accessed:
console.log(document.getElementById('demo').getAttribute); I suggest using HTML5 data-* attributes. Something like that:
<div id="demo" data-myValue="1">...</div> in this case, you can access it using:
element.getAttribute('data-myValue'); //Or using jQuery: $('#demo').data('myValue'); First of all
<div id="demo" align="center" value="1"></div> which is not valid HTML . Read user data attributes or use the following instead:
<div id="demo" align="center" data-value="1"></div> Since "data-value" is an attribute, you must use the getAttribute function to get its value.
var cookieValue = document.getElementById("demo").getAttribute("data-value"); You can try the following:
var theValue = document.getElementById("demo").getAttribute("value"); Value is not a valid div attribute
try it
var divElement = document.getElementById('demo'); alert( divElement .getAttribute('value'));