Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get value of li tag which is in ul tag using getElementById

In this code I am getting in alert 0 insteadof '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);
}
like image 954
Vivek Gondliya Avatar asked May 22 '15 08:05

Vivek Gondliya


People also ask

How to get all li from ul?

In JavaScript, you can use the . getElementsByTagName() method to get all the <li> elements in <ul>. In-addition, you can use the . querySelectorAll() method also to get all the <li>.

How to get ul value in JavaScript?

You can use . innerHTML or . textContent / . innterText to access the content of HTML elements.

How to get all li elements JavaScript?

To get all li elements in an array with JavaScript, we can call the getElementsByTagName method to get all the li elements. Then we can use the spread operator to spread all the items in the node list to an array. to call document. getElementById("navbar") to get the div element.

How to get li tag id in JavaScript?

Inside your handler this will be the clicked element and you can access its id as a property. Ex: $(elem). click(function(){ var id = this.id; //Here this is the DOM element and you can access its id property ///Do something.. })


1 Answers

You need to read attribute value, since HTMLLiElement doesn't have value property:

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

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

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

Then HTML will be valid and IDE's won't complain about unknown attributes.

Check 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>
like image 200
dfsq Avatar answered Oct 03 '22 19:10

dfsq