• First Node
  • How to get li tag value which is in ul tag using getElementById

    In this code, I get a warning of 0 instead of "abc"

    <ul> <li>First Node</li> <li id="repoFolder" value="abc">Lazy Node</li> </ul> <button onclick="rootFolder()">Click Me</button> 

    JS:

     function rootFolder() { alert(document.getElementById("repoFolder").value); } 
    +5
    source share
    4 answers

    You need to read the attribute value since the HTMLLiElement does not have a value property:

     document.getElementById("repoFolder").getAttribute("value"); 

    And since the value attribute is not specified in the specification of the li tag, it is better to use the data attribute (with .getAttribute("data-value") ):

     <li id="repoFolder" data-value="abc">Lazy Node</li> 

    Then the HTML will be valid and the IDE will not complain about unknown attributes.

    Check out the demo below.

     function rootFolder() { alert(document.getElementById("repoFolder").getAttribute('data-value')); } 
     <ul> <li>First Node</li> <li id="repoFolder" data-value="abc">Lazy Node</li> </ul> <button onclick="rootFolder()">Click Me</button> 
    +3
    source

    Try using getAttribute() :

     function rootFolder() { alert(document.getElementById("repoFolder").getAttribute('value')); } 
     <ul> <li>First Node</li> <li id="repoFolder" value="abc">Lazy Node</li> </ul> <button onclick="rootFolder()">Click Me</button> 
    +2
    source
    • You need to replace the line

      Alerts (document.getElementById ("repoFolder") value.); from

      Alerts (document.getElementById ("repoFolder") GetAttribute ('value').);

    +1
    source

    Add the following line:

     alert(document.getElementById("repoFolder").getAttribute('value')); 
    +1
    source

    All Articles