Sudhanshu Saini Sudhanshu Saini - 2 months ago 7x
Javascript Question

traversing ul using array method

I am using the values input by the user to perform the action.
Here is the code:

this is part of the code but u need to see the full code in the above link

var lists = $ul.getElementsByTagName("li");
for (var i = 0; i < lists.length; ++i) {
if (lists[i] == value) {

the first input should take the value in some li
and the second input should take the respective parent ul.


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) {

You have several issues:

  • $ul.getElementsByTagName is not a valid function. Because $ul at this point is a jquery array, 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.