Home > Mobile >  How do I add labels dynamically using jQuery?
How do I add labels dynamically using jQuery?

Time:11-14

I do not know how to use jQuery at all and I really need some help. Here is what I'm trying to do... an example

I need to add those labels next to those without any hard-coding the text in the HTML. I'm very new to jQuery and would really love some help.

HTML

first half of html second pic of html last pic of html

jQuery (This is from a tutorial)

 $("document").ready(function(){
 $("body").append("<p>JSQuery Hello World");
 });



window.addEventListener("DOMContentLoaded", function(evt) {
var elem = document.getElementsByTagName("body")[0];
var para = document.createElement("p");
var text = document.createTextNode("This is regular JS");
para.appendChild(text);
elem.appendChild(para);
});

CodePudding user response:

Solution code

<script src="your jquery src"></script>
<ul id="productList">
    <li data-type="family">Coffee</li>
    <li data-type="child">Tea</li>
    <li data-type="family">Milk</li>
    <li data-type="child">Milk</li>
    <li data-type="family">Milk</li>
</ul>
<script>
    $(document).ready(function () {
        var listItems = $("#productList li");
        listItems.each(function (idx, li) {
            var product = $(li);
            product.append(" - <b> (" product.attr('data-type') ") </b>");
            // and the rest of your code
        });
    });
</script>

Explanation & logic:

  1. Identify li in #productlist and store it in listItems
  2. Loop through every listItems element via each loop
  3. In DOM element here called product, append the value of data property using jquery append() function

Please note: if no data attribute is defined, undefined will be printed instead of value. To resolve this bug you can add an if condition in each loop and then append.

  • Related