Contrasting the process of generating DOM elements by using createElement, setting properties, etc., versus constructing a string of elements and then appending them

I am curious about the distinction between these two methods for creating HTML elements. I cannot seem to find any difference. I simply want to understand if there are any variations based on performance or any other factors.

The first technique involves using built-in JS methods -

var el1 = document.createElement('div');
el1.innerHTML = 'Element Div 1';
var el2 = document.createElement('span');
el2.innerHTML = ' - Span Element';
el2.classList.add('red');
document.body.appendChild(el1);
el1.appendChild(el2);
el1.id = "div";
.red {
    color: red;
    font-size: 13px;
}
#div {
    font-size: 18px;
    color: burlywood;
}

Now the second technique, in just one step -

document.body.innerHTML = '<div id="div">Element Div 1<span class="red"> - Span Element</span></div>';
.red {
  color: red;
  font-size: 13px;
}
#div {
  font-size: 18px;
  color: burlywood;
}

Both of these techniques yield the same outcome and I can easily manipulate each HTML element created in either way.

View Fiddle1 using the first technique
View Fiddle2 using the second technique

Upon observing the two fiddles above, I notice that both methods produce identical outputs. However, the first method requires multiple lines while the second method accomplishes the task in a single line. Is there any performance disparity between them? Any other differences that I may be overlooking?

Feel free to correct me if I am mistaken anywhere.

I acknowledge that the first method retains references to different objects, which can be beneficial later in the code. Nevertheless, my primary inquiry pertains to the difference between creating elements individually with properties versus the second method, which achieves the same result in a single step using strings.

Thank you.

Answer №1

The second scenario is not only quicker, but also more efficient in general.

Consider the following code snippet:

document.body.innerHTML = '<div id="div">Element Div 1<span class="red"> - Span Element</span></div>';

When this code is executed, the browser populates the DOM in a single transaction, anticipating that there will be no interruptions between multiple insertions.

On the other hand, in the first scenario where the DOM is manually populated, browsers need to constantly verify that the DOM is in a stable state, triggering DOM mutation events with each manipulation.

Although the second scenario requires parsing, all modern browsers are equipped with highly efficient HTML parsers.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The toggle class feature of jQuery is malfunctioning when placed inside a different div

Hello everyone, I am currently working on a toggle effect on my webpage. However, I encountered an error when trying to move the button close to another part of the page. The button works fine if it is placed in one part of the HTML, but does not work if i ...

Enhancing the current Node.js, Express, MongoDB, and Socket.io stack with the integration of AngularJS

After spending some time developing a web app using Node.js, Express, MongoDB, Mongoose and Socket.io, I've successfully released version one. Looking ahead to version two, my plan is to revamp the UI completely and switch to a front-end framework lik ...

Incorporating a hyperlink within a list item for an image

Currently, I am attempting to create a clickable image within an unordered list. Although the paragraph is clickable, unfortunately, the image itself is not responding as expected. <ul> <a href="/movies/test/"><li> ...

Retrieve the JSON element from a Backbone model by its unique identifier

I'm diving into Backbone for the first time and I'm facing difficulties making it work smoothly with a JSON data file. Here's how my model looks: window.Test = Backbone.Model.extend({ defaults: { id: null, name: null, }, url: f ...

Error: Unrecognized controller in AngularJS/Ruby on Rails framework

I've been working through the tutorial on implementing an Angular JS / Ruby on Rails app from Thinkster and have encountered a problem. Despite my controllers being listed in the page's sources when inspecting the content, they are not being rec ...

The automatic opening of a modal in a Livewire component is not functioning as expected

I am having trouble displaying a modal when my component initializes. I have tried using $this->emit('show) to open the modal When I add a button in my view, the emit('show') works! However, I want the modal to be automatically shown whe ...

Direct back to the current page post deleting entry from mongodb

After removing data from MongoDB, how can I redirect to the same view (handlebar)? I tried using res.render, but it shows that the website cannot be reached. Thank you for your assistance. Controller Logic var express = require('express'); va ...

Issues encountered with AngularJS directive binding inner content not functioning as expected

I am currently developing a feature toggle directive, which requires a check to be performed in order to display content if the check is successful. I want the directive to replace itself with its content without creating a new child scope (so I'm try ...

Is there a way to expand the clickable area of JQuery sliders?

Check out some of the jquery ui sliders here One issue I am facing is that when you click the slider bar, the tic jumps to that exact part. This can be problematic because the bar is quite thin, making it easy to miss when trying to click on it. I want to ...

Personalize the HTML <input> tag using the attribute type="file"

Within the React site, there is a field where users can select a file from their computer and view the file path. To achieve this functionality, I used an HTML input with type="file"... <div className="inline-flex w-full justify-between&q ...

I'm experiencing difficulties with a JavaScript slideshow in Vegas

After installing the vegas jQuery plugin to my project using npm, I encountered issues when attempting to use it according to the documentation. Despite linking the required vegas.min.js and vegas.min.css files in my HTML, the plugin doesn't appear to ...

Node.js - Passport authentication consistently results in redirection to failure route

I am currently working on creating a login form using passportJs, but I keep encountering the issue of failureRedirect. Despite searching on stack overflow for a solution, I have not found the correct answer yet. Below is my code: Here is how I am crea ...

Eliminate unnecessary words from the sentence

I wrote a sentence but it got split at every space. The data is displayed like this: const escapeRE = new RegExp(/([/\?""])/g); const myDatas = data.map(des => des.Sentence.toLowerCase().replace(escapeRE, '').split(' ')); [ [ ...

How can you identify the specific HTML page that a jQuery selector is targeting?

In an attempt to create jQuery code that counts the number of <img> elements on a website, I encountered a unique challenge. The website consists of 4 separate HTML pages stored in the same folder on the server. Among these pages, only "pics.html" is ...

What is the best way to position the list element to align with the top of a div container?

To see a live example, visit this link. My goal is to create a line that separates two li elements within a nested ul. However, the line ends up taking the width of the container ul instead of the div containing the entire structure. In the provided examp ...

Checking a sequence using a list of strings

I have an array containing a list of IDs: var listId: string[] = []; var newId: boolean; for (let i in data.chunk) { listId.push(data.chunk[i].aliases[0]); } My objective is to compare a new ID with the entire list. If the new ID is found in the list ...

Utilizing CSS variables and HSLA, create a distinctive linear gradient styling

I am encountering an issue with a CSS variable: :root{ --red: hsl(0, 100%, 74%); } Despite defining the variable, it does not work in the following code snippet: .page-wrapper{ background-image: linear-gradient(hsla(var(--red),.6), hsla(var(--red),.6 ...

Is it feasible to send a GET form to two separate views using two buttons?

On one view, I have a form that functions perfectly. http://myurl.com/myapp/filter_objects/?risk__worktask=1&craft=3 In another view, I need to export the filtered list to a PDF. Currently, I store the results in session and access the list from ther ...

Tips for generating a new div for every iteration:

I am currently using asp.net with c# along with a Master Page. I have been attempting to create a new div for each loop in the while statement in order to customize the design as I desire. Is there a way to achieve this or is there an alternative method th ...

What is the best way to update the color of a v-select component?

https://i.sstatic.net/6VOIo.png Currently utilizing Vuetify for my project <v-select id="makeMeBlue" dense outlined :items="form.values.urlTypes" label="Single or Multi URL" v-model="form.values.urlType" ...