8

I have a basic HTML list like below...

<ul class="test_ul">
    <li class="item" id="item1">
        Item 1
    </li>
    <li class="item" id="item2">
        Item 2
    </li>
    <li class="item" id="item3">
        Item 3
    </li>
    <li class="item" id="item4">
        Item 4
    </li>
</ul>

I am using javascript to try and grab the id of each list item and then use a loop to check each one against a string. I have this so far..

var myvariable
myvariable = "item2"
items = document.getElementsByClassName("item");
for (i = 0; i < items.length; i++) {
    console.log(i);
    console.log(item[i]);
}

This isn't working for me, is it because it is not really an array?

7
  • 2
    console.log(items[i]); Commented Jun 3, 2017 at 16:08
  • getElementsByClassName => "Returns an array-like object of all child elements which have all of the given class names.", you'll have to convert it to an array. Commented Jun 3, 2017 at 16:10
  • What do you mean by “not working”? So far you just log the indices of each element in items. Commented Jun 3, 2017 at 16:10
  • 1
    item isn’t defined anywhere. Commented Jun 3, 2017 at 16:11
  • 1
    You mispelled items in the log statement. Commented Jun 3, 2017 at 16:22

6 Answers 6

8

You're logging the index i, instead, use items[i].id to get the id of the matched element. Something like this

var items = document.getElementsByClassName("item");
for (i = 0; i < items.length; i++) {
  console.log(items[i].id);
}
<ul class="test_ul">
  <li class="item" id="item1">
    Item 1
  </li>
  <li class="item" id="item2">
    Item 2
  </li>
  <li class="item" id="item3">
    Item 3
  </li>
  <li class="item" id="item4">
    Item 4
  </li>
</ul>

Sign up to request clarification or add additional context in comments.

Comments

3

Using ES6 (might need to transpile or add polyfills for older browsers):

// Get the DOMCollection of node corresponding to the item class
var items = document.getElementsByClassName("item")
// Transform the DOMCollection to an array and map item.id
  , ids = Array.from(items).map(item => item.id);
  ;    
console.log(ids);
<ul class="test_ul">
    <li class="item" id="item1">
        Item 1
    </li>
    <li class="item" id="item2">
        Item 2
    </li>
    <li class="item" id="item3">
        Item 3
    </li>
    <li class="item" id="item4">
        Item 4
    </li>
</ul>

Using ES5 only:

var items = document.getElementsByClassName("item")
  , ids = []
  ; 
for(var i = 0, c = items.length; i<c; i++) {
    ids.push(items[i].id);
}
console.log(ids);
    <ul class="test_ul">
        <li class="item" id="item1">
            Item 1
        </li>
        <li class="item" id="item2">
            Item 2
        </li>
        <li class="item" id="item3">
            Item 3
        </li>
        <li class="item" id="item4">
            Item 4
        </li>
    </ul>

4 Comments

Note that from() has limited browser support
@charlietfl polyfills/transpilers exist :)
Right but that was not mentioned. If OP didn't know and ran this in IE would fail
@charlietfl thanks, I added the info. I'll also provide a more compatible code.
2

You could borrow Array#map for an array like object and return just the id property of the objects.

var result = [].map.call(document.getElementsByClassName("item"), function(o) {
        return o.id;
    });

console.log(result);
<ul class="test_ul">
    <li class="item" id="item1">Item 1</li>
    <li class="item" id="item2">Item 2</li>
    <li class="item" id="item3">Item 3</li>
    <li class="item" id="item4">Item 4</li>
</ul>

Comments

2

My understanding is, you want to loop through this list of items and find a match of the item based on a specified string.

What you've done so far with the classes is good. This will allow you to reference all the list items, but there isn't really a need for the IDs based on what I think it is that you're trying to do.

If I were you, I would utilize a querySelectorAll, which returns an iterable array of HTML nodes that we can do whatever we want with.

Here's my code.

let listItemArray = document.querySelectorAll('.item');
console.log(listItemArray);
const SEARCH_STRING = 'Item 1'

for(let i=0; i<listItemArray.length; i++) {
  if(listItemArray[i].innerText === SEARCH_STRING) {
    console.log(`The item was found! ${listItemArray[i]}`); // This syntax is called a query string. Powerful stuff. Look them up.
  }
}
<ul class="test_ul">
    <li class="item" id="item1">
        Item 1
    </li>
    <li class="item" id="item2">
        Item 2
    </li>
    <li class="item" id="item3">
        Item 3
    </li>
    <li class="item" id="item4">
        Item 4
    </li>
</ul>

Comments

2

Add ID ="lstUsers" to ul element < you're registered with DOM now

for (var i = 0; i < lstUsers.children.length; i++) {
   alert( lstUsers.children[i].innerText);
}

#lstUsers  <--css with your id you shrink your HTML down this way...

Comments

2

While all of the answers here are equally good, and this qs is old(2017)
I am posting this for knowledge sharing

We can use:

items = document.querySelectorAll(".item");//Get items
items.forEach(function(item) {
  console.log(item);/*Use variable item for any need*/
});

If you need the index of item as well then use

items = document.querySelectorAll(".item");//Get items
items.forEach(function(item,index) {
  console.log(item, index);/*Use variable item & index for any need*/
});

The best of this is that it doesn't need any loop or extra variable like i. Also, it do not make use of a loop like for or while, but a function like forEach(), where forEach is a human-readable word

Note: forEach() cannot be used with getElementsByClassName() ,it supports only querySelectorAll()

Working snippet:

items = document.querySelectorAll(".item");//Get items
items.forEach(function(item) {
  console.log(item);/*Use variable item for any need*/
});

console.log("The below log is with index");

items = document.querySelectorAll(".item");//Get items
items.forEach(function(item,n) {
  console.log(n,item);/*Use variable item for any need*/
});
<ul class="test_ul">
    <li class="item" id="item1">Item 1</li>
    <li class="item" id="item2">Item 2</li>
    <li class="item" id="item3">Item 3</li>
    <li class="item" id="item4">Item 4</li>
</ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.