简体   繁体   中英

Set a value on li using jQuery

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.

 $("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> 

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> 

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM