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.
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.
-
Only
input
andtextarea
can havevalue
IIRC... – Jack Bashford Commented May 16, 2019 at 8:43 -
li
doesn't have a value attribute if you want to save id or something usedata-value
attribute – Sunil Kashyap Commented May 16, 2019 at 8:44 -
2
You can set a
data-value
attribute, which would likely be more correct for whatever it is you're trying to do. – David Commented May 16, 2019 at 8:44 -
@JackBashford what about
button
,select
etc etc? – Roko C. Buljan Commented May 16, 2019 at 9:06 -
1
@RoryMcCrossan seems like while we were sleeping they reintroduced
value
in HTML5 for LI elements inside OL developer.mozilla/en-US/docs/Web/HTML/Element/li#Attributes – Roko C. Buljan Commented May 16, 2019 at 9:11
4 Answers
Reset to default 2
$("li").attr("value",1); // set the attribute and value
alert($("li").attr("value")); // show the value
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ol>
<li></li>
</ol>
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./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./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li></li>
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./jquery-3.3.1.js"></script>
<ul>
<li></li>
</ul>
Also note you need a <ul>
or <ol>
element.
jquery is simple,
Just give id to li
$('#area1').attr('area', '1')
<script src="https://ajax.googleapis./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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744836020a4596266.html
评论列表(0条)