How to get value of a div using javascript

前端 未结 6 2124
情歌与酒
情歌与酒 2020-11-27 21:47

This is my div:

By Color

相关标签:
6条回答
  • 2020-11-27 22:00

    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

    0 讨论(0)
  • 2020-11-27 22:04

    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');
    
    0 讨论(0)
  • 2020-11-27 22:09

    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);
    }
    
    0 讨论(0)
  • 2020-11-27 22:17

    Value is not a valid attribute of DIV

    try this

    var divElement = document.getElementById('demo');
    alert( divElement .getAttribute('value'));
    
    0 讨论(0)
  • 2020-11-27 22:23

    You can try this:

    var theValue = document.getElementById("demo").getAttribute("value");
    
    0 讨论(0)
  • 2020-11-27 22:24

    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"); 
    
    0 讨论(0)
提交回复
热议问题