In the example of a very common scenario, where we need to change the style of an entire class of elements, we have (simplified and generalized) code that looks like this:
var elements = document.getElementsByTagName('div'); for (var i = 0; i < elements.length; i++) if (elements[i].className == 'HideMe') elements[i].style.visibility = 'hidden';
It gets all div elements from the document, iterates over them and changes the visibility of those that have the "HideMe" class for "hidden" ones. This code, on the other hand:
document.innerHTML.replace(/class="HideMe"/mg, 'class="HideMe" style="visibility: hidden"');
will add an invisibility style to everything that has the "HideMe" class. I'm new to JavaScript and don't get me wrong, but every example, every tutorial I've seen so far, teaches the first method. Is a one-line, one function call, replacement algorithm created by a more intelligent being should be faster and less resource-intensive than any cycle with an if ? The question is actually more general, why not:
document.innerHTML.replace('id="foo"', 'id="bar"');
instead:
document.getElementById('foo').id = 'bar';
The tested code is exactly the same, but for performance I will probably have to change the style of thousands of elements so that I can measure any significant differences. Are there any good, reasoned reasons why we should stick to one method over another?
Ulrik source share