Good practice when manipulating HTML controls through Javascript

What is a good way to control HTML controls?

By creating an HTML element?

var select = document.getElementById("MyList"); var options = ["1", "2", "3", "4", "5"]; for (var i = 0; i < options.length; i++) { var opt = options[i]; var el = document.createElement("option"); el.Text = opt; el.value = opt; el.innerHTML = opt; select.appendChild(el); } 

Or by controlling HTML:

  var options = new Array(2); options [0] = '1'; options [1] = '2'; options [0] = '<option>' + options [0] + '</option>'; options [1] = '<option>' + options [1] + '</option>'; var newHTML = '<select>' + options [0] + options [1] + '</select>'; selectList.innerHTML = newHTML; 

Which one is good practice? Is preferred over others in specific conditions?

+4
source share
3 answers

Always the first approach. if you use the innerhtml style, the browser itself creates.

+1
source

The 1st approach looks more modular and reusable. You can put the lines inside the for loop in a method and call that method.

+4
source

The first method is better than the second, i.e.

** Creating an HTML element is better than manipulating the DOM "

Reason: working with the DOM may cause the browser to switch.

For example: suppose you need to replace an element with a DOM that already exists.

Using approach:

  • Create a DOM element . You create an item. Add verified attributes to it and replace it. The item will be added at a time, and there will be only one recount of the document .

  • Manipulating the DOM . You need to add and remove attributes or elements one at a time. This may cause the browser to initiate payment of all elements and attributes that are being processed. This will require significant resources for rendering the document flow when manipulating elements .

Thus, creating a dom element is much smoother, since the browser does not have to display the document flow again.

* EDIT: * If you need to insert many elements, the best way is to create a fragment of the document . The document fragment is in memory, not in the DOM tree. Thus, adding elements to it DOES NOT cause distortions. As the docs say:

Since the document fragment is in memory, and is not part of the main DOM tree, adding child elements to it does not cause a page overflow (calculating the element position and geometry). Therefore, the use of document fragments often leads to increased productivity.

+1
source

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


All Articles