0

I'm creating a loop which finds all elements in a class that contain the character 'L' and performing an innerHTML command to each. This loop seems to work fine until I get to actually do i.innerHTML = '', where the i's is the array for L strings. Why can't I do it like this? If I do a console.log(i); inside the if statement I get the correct array.

letts = document.getElementsByClassName('span2');
for(i in letts){
        if(i.indexOf('L') !== -1){
                i.innerHTML = '';
        }
}

3 Answers 3

3

You do it wrong.

i in for .. in loop refers to object property name. It is better to iterate NodeList collections (as arrays) with simple for loop as described in below.

var letts = document.getElementsByClassName("span2");
for (var i = 0, len = letts.length; i < len; i++) {
    if (letts[i].innerHTML.indexOf("L") > -1) {
        letts[i].innerHTML = "";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

your i in for-- in loop refers to the index (0 based). You should use

for(i in letts){
        if(letts[i].indexOf('L') !== -1){
   ...

or

for (var i = 0, i < letts.length; i++) {
...

Comments

0

A foreach loop is handy in such situations.

Arrays have a forEach method, but NodeLists don't, for some reason. You could use one of:

  • .forEach function of underscore.js
  • .each function of JQuery (or pretty much any framework)
  • or the [].forEach.call() trick.

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.