Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value of a div using javascript

Tags:

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,.

like image 723
srinu Avatar asked Jun 28 '12 05:06

srinu


People also ask

How do I get the content of a div?

Use the textContent property to get the text of a div element, e.g. const result = element. textContent . The textContent property will return the text content of the div and its descendants. If the element is empty, an empty string is returned.

Does div have a value?

None of them are declared, or have values assigned to them. div elements don't have a . value property that would get submitted to the backend; use an input element for that.

How do I get the innerHTML value?

Firstly, to get the innerHTML value of any tag, you either need that tag to have its 'id' property or 'name' property set. Then you can respectively use the 'document. getElementById(yourTagIdValue). innerHTML' or 'document.

How div is used in HTML?

Definition and UsageThe <div> tag defines a division or a section in an HTML document. The <div> tag is used as a container for HTML elements - which is then styled with CSS or manipulated with JavaScript. The <div> tag is easily styled by using the class or id attribute.


2 Answers

DIVs 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); } 
like image 167
JAAulde Avatar answered Oct 09 '22 18:10

JAAulde


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

like image 31
Guidhouse Avatar answered Oct 09 '22 17:10

Guidhouse