Reputation: 1141
In an example of a very common scenario, where we need to change the style of an entire class of elements, we have a (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 the div
elements from the document, loops through them, and changes the visibility of ones that have class "HideMe" to "hidden". On the other hand, this code:
document.innerHTML.replace(/class="HideMe"/mg, 'class="HideMe" style="visibility: hidden"');
will insert the the invisibility style to everything that has class "HideMe". I am new to JavaScript
, and don't get me wrong, but every example, every tutorial that I've seen so far, teaches the first method. Shouldn't a one-liner, a single function call, a replace algorithm created by a more intelligent being, be faster and less resource-intensive than any kind of loop wiith an if
statement? The question is actually more general one, why not do:
document.innerHTML.replace('id="foo"', 'id="bar"');
instead of:
document.getElementById('foo').id = 'bar';
The inspected code is absolutely the same, but for the performance, I would probably need to make it change the style of thousands of elements so I can measure any significant difference. Are there any good, well-argued reasons why we should favor one method over the other?
Upvotes: 5
Views: 460
Reputation: 193271
Regexp solution is very bad and should never be used (except maybe in very specific cases). The main reason why is that you don't want to replace innerHTML
of the body
. What happens in this case is that entire DOM tree has to be rebuild and rerendered, causing not only UX lags and potential performance issues but which is more important - loss of all bound event handlers.
On the other hand, proper usage of DOM manipulation methods should give you the best performance and cleaner and easier to read code.
However, the first method you mention is also not very good: you should avoid changing CSS styles with Javascript. Ideal approach would be to add one more modifier class to elements, for example:
var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++)
if (elements[i].className == 'HideMe')
elements[i].className += ' HideMe-hidden';
// or elements[i].classList.add('HideMe-hidden');
where in CSS you would have
.HideMe-hidden {
visibility: hidden;
}
This is the most flexible and optimal solution.
Upvotes: 6