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);
}
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>.
You can use . innerHTML or . textContent / . innterText to access the content of HTML elements.
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.
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.. })
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With