Effective JavaScript style change for the entire class of elements

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?

+5
source share
1 answer

The Regexp solution is very bad and should never be used (except, perhaps, in very specific cases). The main reason you don't want to replace innerHTML with body . What happens in this case is that the DOM tree of integers needs to be rebuilt and rewritten, causing not only UX delays and potential performance problems, but more important - the loss of all event handlers.

On the other hand, the proper use of DOM manipulation methods should give you better performance and cleaner, easier to read code.

However, the first method you mentioned is also not very good: you should avoid changing CSS styles using Javascript. An ideal approach would be to add another modifier class to the 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 will have

 .HideMe-hidden { visibility: hidden; } 

This is the most flexible and optimal solution.

+6
source

Source: https://habr.com/ru/post/1233433/


All Articles