Reputation: 19
How can we set a value
attribute inside a <li></li>
element using jQuery/JavaScript?
I have set innerHTML
inside an element but I don't know how to set a value
on it without set value like <li value="1"></li>
<li></li>
<script>
document.getElementById("area1").innerHTML = "1";
</script>
I want to set a value from jQuery as like above innerHTML
given not from HTML tag.
Upvotes: 0
Views: 6795
Reputation: 7769
jquery is simple,
Just give id to li
$('#area1').attr('area', '1')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<div id="banner-message">
<li id="area1">Hello LI </li>
</div>
have a look to code and let me know, if i can help you
Upvotes: 1
Reputation: 81
$("li").attr("value",1); // set the attribute and value
alert($("li").attr("value")); // show the value
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ol>
<li></li>
</ol>
Upvotes: 2
Reputation: 44107
You can't have value
inside an li
- you can use data-value
instead:
$("li").data("value", 1);
console.log($("li").data("value"));
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<ul>
<li></li>
</ul>
Also note you need a <ul>
or <ol>
element.
Upvotes: 1
Reputation: 5121
As said, it doesn't have a lot of standard functions but you can do it like this.
$('li')[0].setAttribute('value',1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li></li>
It would be better though if you use a data attribute.
$('li')[0].setAttribute('data-value',1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li></li>
Upvotes: 1