Sudhanshu Saini Sudhanshu Saini - 4 months ago 8
jQuery Question

Traversing list items using array method

I am using the values input by the user to perform this action.

Here is the full code: https://jsfiddle.net/7196dfyz/

This is part of the code where the elements are traversed, where I'm having trouble:



var lists = $ul.getElementsByTagName("li");
for (var i = 0; i < lists.length; ++i) {
if (lists[i] == value) {
$("ul").css("background-color","black");
}
}





The first input should take the value in some
li

and the second input should take the respective parent
ul
class name.

Answer

I think this is what you're looking for. (Here is an updated jsfiddle):

function func() {
    var key = $("#key").val();
    var value = $("#entry").val();
    var $ul = $("." + key);
    var lists = $ul.find("li");
    for (var i = 0; i < lists.length; ++i) {
        console.log($(lists[i]).text(), value);
        if ($(lists[i]).text() === value) {
            $(lists[i]).css("background-color","black");
        }
    } 
}

You have several issues:

  • $ul.getElementsByTagName is not a valid function. Because $ul at this point is a jQuery array-like object, it wont work. You'd need to do $ul[0].getElementsByTagName, or simply use jQuery's find() like my example above.
  • You're trying to compare lists[i] to value, which happens to be an HTML element. When comparing to a string, it will return <li>Say</li> which will never match anything you type in. Using $(lists[i]).text() should get you what you need.
  • $("ul").css("background-color","black");: You were setting every ul to black if a match was found. I assume you only want to match the one that was matched. $(lists[i]).css("background-color","black"); fixes this.

You can even simplify this entire function down to this:

function func() {
    var key = $("#key").val();
    var value = $("#entry").val();
    $("." + key).find("li").filter(function() {
        return $(this).text() === value;
    }).css("background-color","black");
}

Broken down:

  • $("." + key): Find the ul that has the class of key.
  • .find("li") Find all list items within each unordered list found.
  • .filter(...) For each element in this list, and return to me only the items that match my criteria: $(this).text() === value.
  • And finally .css("background-color","black"): Set all the background colors to black of the list items that were returned from the filter() function.
Comments