0

My code should insert HTML content in all divs that have a predefined class name, without using jQuery and at least compatible with IE8 (so no getElementsbyClass).

The html:

<div class="target">1</div>
<div class="target">2</div>
<div class="target">3</div>
<div class="target">4</div>

The javascript:

var elems = document.getElementsByTagName('*'), i;
    for (wwi in elems) {
        if((' ' + elems[wwi].className + ' ').indexOf(' ' + "target" + ' ') > -1) {
            elems[wwi].innerHTML = "YES";
            //elems[wwi].innerHTML = "<div>YES!</div>";
        }
    }

You can try it here.

As you can see inside each div the word YES is printed. Well the if you comment elems[wwi].innerHTML = "YES"; and replace that for elems[wwi].innerHTML = "<div>YES!</div>" the code fails. I suppose is because inserting div elements modify the DOM and in consequence the FOR cycle fails. Am i right?

Well i can solve this pretty ugly by recalling the for cycle each time i make an innerHTML, and when i insert the code i can add a class (like data-codeAlreadyInserted=1) to ignore the next time the FOR pass in that div. But again, this is pretty much a very bad solution since for an average site with many tags I can even freeze the user browser.

What do you think? lets suppose i dont know the amount of tags i insert on each innerHTML call.

3 Answers 3

1

"I suppose is because inserting div elements modify the DOM and in consequence the FOR cycle fails. Am i right?"

Pretty much. Your elems list is a live list that is updated when the DOM changes. Because you're adding a new div on every iteration, the list keeps growing and so you never get to the end.

To avoid this, you can either do a reverse iteration,

for (var i = elems.length-1; i > -1; i--) {
    // your code
}

or convert the list to an Array.

var arr = [];

for (var i = 0, len = list.length; i < len; i++) {
    arr.push(elems[i]);
}

for (i = 0; i < len; i++) {
    // your code
}
1
  • @DomingoSL: Your elems list. And actually, whether or not it becomes an infinite loop or simply skips some elements will depend on the browser's implementation of for-in.
    – user2437417
    Jun 26, 2013 at 13:01
0

Another way is to use replaceChild instead of innerHTML. It works better and it's way faster:

var newEl = elem[wwi].cloneNode(false);
newEl.innerHTML = html;
elem[wwi].parentNode.replaceChild(newEl, elem[wwi]);
5
  • So cloning a node, settings its .innerHTML and then swapping the original with the clone is faster than just setting the .innerHTML of the original?
    – user2437417
    Jun 26, 2013 at 12:57
  • @Crazy-Train, yes, is faster on all browsers except for IE... I've tested it myself, I have a single page app that became much more responsive when I changed innerHTML to replaceChild.... Jun 26, 2013 at 13:42
  • But you're still using .innerHTML in your answer. Did your tests do the same?
    – user2437417
    Jun 26, 2013 at 13:44
  • Yes, I'm still using innerHTML but on an empty node! Which is very different than using it on a node full of children... it really improved (a lot!!) my app's performance. Jun 26, 2013 at 13:48
  • cloneNode(false) means it will clone only the element, not it's children. Jun 26, 2013 at 13:49
0

You can take a copy of the live node list:

var nodes = [];
for (var i = 0, n = elems.length; i < n; ++i) {
    nodes.push(elems[i]);
}

and then use a proper for loop, not for ... in to iterate over the array:

for (var i = 0, n = nodes.length; i < n; ++i) {
    ...
}

for ... in should only be used on objects, not arrays.

7
  • can you please give an example?
    – DomingoSL
    Jun 26, 2013 at 12:50
  • @DomingoSL I thought I had...?!
    – Alnitak
    Jun 26, 2013 at 12:51
  • Your .slice.call isn't going to work in IE8, because IE8 requires native objects as the this value of its native methods.
    – user2437417
    Jun 26, 2013 at 12:56
  • I mean using my code, im not a front end dev, so im having issues to understand your answer, if you provide me a complete code maybe i can get it faster
    – DomingoSL
    Jun 26, 2013 at 12:56
  • 1
    @CrazyTrain I am so glad I don't have to regularly write code for that non-conformant piece of shite that is any IE < 10
    – Alnitak
    Jun 26, 2013 at 13:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.