I do not know how to use jQuery at all and I really need some help. Here is what I'm trying to do...
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
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:
- Identify
li
in#productlist
and store it in listItems - Loop through every listItems element via each loop
- In DOM element here called
product
, append the value of data property using jqueryappend()
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.