最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript foreach loop on list items - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Jun 3, 2017 at 16:11 fightstarr20 asked Jun 3, 2017 at 16:06 fightstarr20fightstarr20 12.6k45 gold badges170 silver badges299 bronze badges 7
  • 2 console.log(items[i]); – Suresh Atta 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. – WilomGfx 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. – Sebastian Simon Commented Jun 3, 2017 at 16:10
  • 1 item isn’t defined anywhere. – Sebastian Simon Commented Jun 3, 2017 at 16:11
  • 1 You mispelled items in the log statement. – RJM Commented Jun 3, 2017 at 16:22
 |  Show 2 more comments

6 Answers 6

Reset to default 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>

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>

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>

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>

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...

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>

发布评论

评论列表(0)

  1. 暂无评论