"Creating a new element caused the inline-block display to malfunction

Can someone explain why the createElement function is not maintaining inline-block whitespace between elements?

Example problem

First rectangle shows normal html string concatenation:

var htmlString = '<div class='inline-block'...></div>'
$(parent).html(htmlString);

The second rectangle displays output using createElement for DOM elements:

var htmlElement = createElement('div');

htmlElement.className('inline-block');

...appendChild(htmlElement);

What causes this difference in output?

Thank you

Answer №1

If you want to create a space between elements, you can achieve this by inserting a textNode between them.

When adding a String to HTML, the string is parsed as HTML which may result in the combination of multiple whitespaces into a single whitespace, generating a textNode by the HTML parser. However, when using createElement, textNodes need to be created manually by the user. Think of it as taking control and responsibility for generating HTML yourself.

var parent = document.getElementById('parent');
var htmlString = document.createElement('div');
htmlString.className= 'inline-block';
var textNode = document.createTextNode(' ');
var htmlString2 = document.createElement('div');
htmlString2.className= 'inline-block';
parent.appendChild(htmlString);
parent.appendChild(textNode);
parent.appendChild(htmlString2);
.inline-block {
  display: inline-block;
  width: 100px;
  height: 20px;
  border: 1px solid red;
}
<div id="parent"></div>
\n can also be used for the same purpose, if you were attempting to add a line break.

var parent = document.getElementById('parent');
var htmlString = document.createElement('div');
htmlString.className= 'inline-block';
var textNode = document.createTextNode('\n');
var htmlString2 = document.createElement('div');
htmlString2.className= 'inline-block';
parent.appendChild(htmlString);
parent.appendChild(textNode);
parent.appendChild(htmlString2);
.inline-block {
  display: inline-block;
  width: 100px;
  height: 20px;
  border: 1px solid red;
}
<div id="parent"></div>

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

Ways to prevent the input value from rising on a number type input when the up button is pressed

I'm curious about whether it's possible to prevent the input value from increasing when I press the up button on a type number input. Any ideas? ...

There appears to be a glitch preventing Phonegap from properly syncing with Google Analytics

I'm currently developing an app using PhoneGap and I wanted to integrate Google Analytics into it. After installing this plugin via the CLI, I inserted the following lines of code within my deviceReady event: analytics.startTrackerWithId('UA-*** ...

Is it possible to dynamically load records in real time with the help of PHP and jQuery?

I developed a custom system using PHP that allows users to post status messages, similar to a microblog. The system utilizes a database table structured like this: posts_mst ------------------ post_id_pk post_title post_content date_added Initially, I su ...

Exploring the power of nested routes in React Router 4: accessing /admin and / simultaneously

I'm encountering an issue with nested routing. The URLs on my normal site are different from those on the /admin page, and they have separate designs and HTML. I set up this sample routing, but whenever I refresh the page, it turns white without any ...

What is the most efficient way to enable seamless communication between sibling components in Vue.js 2?

Just starting out with Vue.js 2 and I'm really enjoying it so far despite being new to it. Currently using the latest version. I've begun working on my first larger application and ran into a scenario right off the bat where I have a main app co ...

Counting money using jQuery

I am a beginner when it comes to jQuery. I have a specific project in mind where I need to create a dynamic money counter that starts at $1,000,000.34. The last two digits (34) should be incrementing rapidly while the one million dollars keep increasing a ...

Generate a key pair using the cryto library and then use it with the json

There's a new method called generateKeyPair in node 10, and I am utilizing it in the following way: const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", { modulusLength: 4096, publicKeyEncoding: { type: "spki", format: "pem ...

Transforming the hide/show functionality from JQuery to Vue

I created some hide/show panels using jQuery that I want to implement in Vue. However, when I try to integrate the jQuery functions into Vue, the functionality doesn't seem to work properly. The panels are not hiding/showing as expected. Does anyone ...

What is the point of the horizontal scroll bar in WP Thesis?

There seems to be a horizontal scroll bar appearing at the bottom of my site, even though there is no content extending beyond the visible area. Can anyone provide guidance on how to fix this issue? My website is built on Wordpress 3.0 and utilizes the Th ...

How come the text is not centered when I use text-align:center; on my class "text5"?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Homepage</title> ...

Struggling to maintain context with axios in React despite diligent use of arrow functions

In my component, I have a function for posting data. Although it works well, the context of my component is lost in the success message. This is puzzling because I am using arrow functions. Why does the "this" context get lost in this situation? The issu ...

Steps to make a sub Post or page on WordPress

Seeking to add sub posts within my website's main posts. The URL structure for the main post will be: site.com/post-title I envision sub posts following this format: site.com/post-title/subpost1 site.com/post-title/subpost2 site.com/post-title/ ...

Guide to using vite-plugin-rewrite-all in conjunction with Quasar for Vue 3 - or alternative method to enable periods in paths

Encountering a 404 error when using quasar+vite in vueRouterMode: 'history' mode with paths containing a period/dot in the id? This issue has been discussed in various places: https://github.com/vitejs/vite/issues/2415 https://github.com/vitejs/ ...

Utilizing Jquery to enhance slide image transitions with navigational links

As a newcomer to jQuery, I am attempting to create a slider using jQuery. Here is the script I have so far: $(function() { var bgCounter = 0, text = [ 'some html code here', 'some html code here', 'some ...

I'm having trouble grasping the sequence of events in this async example

Currently, I'm delving into the world of JavaScript and Node.js, but I find myself facing challenges with asynchronous execution. I have a piece of code that may not be following best practices, but I am eager to understand why the file remains open w ...

Adjust the Bootstrap Navbar by positioning one navigation item to the right side

I want to align the logout button to the right within my bootstrap navbar. https://i.stack.imgur.com/PDvSv.png Here is a demonstration of the current behavior: https://codepen.io/agrawalo/pen/mdbKYLX Code: <nav class="mb-1 navbar navbar-expand-sm na ...

Changing a single state in React results in the modification of both states simultaneously

Whenever I attempt to modify one state, I find that another state is inexplicably changing as well. I've scoured my code for the issue but can't seem to pinpoint it. What steps should I take next? Here's the snippet of code in question: impo ...

What is the best way to update the content of a modal using jQuery and AJAX?

Despite previous inquiries on this matter, none of the answers provided have been helpful to me. Therefore, I am addressing the issue again... I am currently developing the frontend of a website that does not involve any backend functionality (no server c ...

The "Key" function from Object.keys does not yield true when compared to an identical string

Object.keys(data).forEach((key) => { bannerData[key] = data[key][0]; console.log(key); if (key == "timestamp") { labels.push(data[key]); console.log("wtf"); console.log(labels); ...

What is an alternative method to retrieve form data without relying on bodyParser?

When it comes to accessing posted form data without using bodyParser, what alternatives are available? How exactly does bodyParser grant access to the data in req.body? Additionally, I am curious about the inner workings of this process on a deeper level. ...