Could someone clarify why inline-block items appended with jQuery seem to lose their spacing?

Currently, I am working on a project that involves cloning objects and adding them to the same parent. However, when I animate these objects, my calculations are always slightly off. Upon further investigation, I discovered that inline-block items have trailing spaces, which do not get included when appending a cloned item using jQuery. This inconsistency makes it difficult for me to work with the elements.

After inspecting the elements in browser tools, I found that they appear identical and adjusting margins and padding does not make a difference. I'm not sure if this is a bug or if I am overlooking something essential. You can test this issue yourself by following this link: https://jsfiddle.net/kd5opn7j/2/

$('ul').find('li').each(function(){
  $('ul').append($(this).clone());
});
li {
  display: inline-block;
  width:50px;
  height:50px;
  background: #555;
}
<ul>
    <li></li>
    <li></li>
    <li></li>
</ul>

Answer №1

The spacing between the boxes is a result of the structure in the code with newlines and indentation. When jQuery appends elements, it alters the DOM directly without maintaining the original formatting from the markup. It only adds the specified elements.

After jQuery has appended the new elements, your markup will actually look like this:

<ul>
    <li></li>
    <li></li>
    <li></li>
<li></li><li></li><li></li></ul>

The inspector presents elements in a hierarchical manner for better organization but does not show the exact markup generated.

To maintain the white space between elements, you can workaround by adding a literal space before or after each new element:

$('ul').find('li').each(function(){
  $('ul').append(' ').append($(this).clone());
});

If necessary, to keep the original indentation style (visible in parent's innerHTML)...

$('ul').find('li').each(function(){
  $('ul').append('    ').append($(this).clone()).append('\n');
});

Keep in mind that visually there will be no discernible difference as consecutive spaces and newlines are condensed into one space during rendering.

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

Modify every bit of HTML code

When utilizing JQuery AJAX, I am in need of sending data to a page and then receiving data back. The task is to remove all tags, including html, and set up the new page as shown below: <html> <head></head> <body>Example</body> ...

Is it possible to utilize onclick for various table cells in jQuery?

I have a situation where I need to loop through dates and display table content accordingly. Could someone please assist me in figuring out how to do this? index.html.erb <% @batches.each do |batch| %> <tr> **<td class = "pie" id ...

The navbar tag is not functioning properly within Reactjs

Need help with creating a web header in ReactJS? I'm still learning Javascript and struggling to position the menu on the right side using bulma CSS. Can anyone offer some guidance? import React, { Component } from 'react'; import './H ...

When the button is clicked, redirect to a new page and submit a form using AJAX with data obtained from the click event

I have a page called 2.html where inputting an ID number results in some output being displayed. This functionality is achieved using Ajax post method, sending data along with the data parameter. I also have another page named 1.html that contains a list o ...

Styling a Fixed Header in CSS/HTML - Scroll Effect

Is it possible to hide only the upper part of the nav-bar, similar to the behavior in WhatsApp? I am using material-ui for this particular use-case. Currently, my implementation causes the app-bar to extend only when the scroll position is less than 48px, ...

Hide only the table that is being clicked on, not all tables

Essentially, I am using document.querySelectorAll() to retrieve an array of div elements. In my function, handleClick(), each time the button is clicked, I want to hide the table associated with that specific button. This is the current situation: https:/ ...

Tips for resolving the setAttribute() function error message: "Argument of type 'boolean' is not assignable to parameter of type 'string'"

I am currently working on a function that dynamically updates the HTML aria-expanded attribute based on whether it is true or false. However, when I declare element as HTMLElement, I encounter an error stating Argument of type 'boolean' is not as ...

Unable to view Bootstrap modal upon click

Whenever I attempt to display a modal using Bootstrap, it mysteriously appears upon page refresh but fails to show up when the button is clicked. Ideally, I want the modal to only appear when the user clicks on the button. The structure of my html file lo ...

AngularJs' dir-paginate feature generates a distinct row number for each table row it creates

Is there a way to assign row numbers to each table row generated by dir-paginate in AngularJS? I've tried two methods but encountered errors with both. First approach : <tr dir-paginate='customer in Customers| itemsPerPage: 10'> ...

Using multiple `setState` calls without synchronization can lead to issues, especially when one of them uses a value obtained from `

In my discovery: When there are two instances of setState The first one is invoked with a value obtained from await Both calls occur in the same thread It results in a scenario where one state is updated while the other remains unchanged. For instance: ...

Emphasize the cells located in the bottom left quadrant of the table (triangular shape)

I've dynamically created an HTML table with a specified number of rows and columns. The next step is to highlight the cells in the bottom left half of the table with a light red color, forming a triangle pattern similar to the one shown in this link. ...

Using node-fetch version 3.0.0 with jest results in a SyntaxError stating that import statements cannot be used outside a module

Recently, I've been updating my API to utilize node-fetch 3.0.0. One major change highlighted in their documentation is that node-fetch is now a pure ESM module. Click here for more information on the changes This update caused some of my unit tests ...

jqGrid search functionality malfunctioning

My code seems to have an issue where the search function is not working correctly and the 'Edit' feature is displaying but not saving into the database. I attempted to follow the instructions provided in this URL, http://www.trirand.com/jqgridwik ...

Utilize the JavaScript Email Error Box on different components

On my website, I have implemented a login system using LocalStorage and would like to incorporate an error message feature for incorrect entries. Since I already have assistance for handling email errors on another page, I am interested in applying that sa ...

Utilizing JavaScript to iterate through objects retrieved via Ajax calls

Recently, I've been diving into the world of Javascript and delving deep into AJAX. Utilizing Vanilla JS along with simple AJAX, my current task involves fetching a user object from a URL based on the user's input ID. Despite attempting to use .d ...

Is it possible for HTML to provide alternative text for unique characters, such as accented characters?

I have a vision for HTML support that may incorporate the following: <span alt="Antonin Dvorak">Anton&iacute;n Dvo&#345;&aacute;k</span> In this scenario, if a browser cannot display special characters, it would default to showing ...

apply jQuery to add a class to the parent element when clicked

I am currently facing an issue with my code. It was working fine in jsFiddle, however, when I try to use it outside of fiddle, I am getting errors and it's not working properly. $('.down-photo').click(function() { $(this).parent(&apos ...

`Displaying the Quantity of Items Depending on the Product Chosen in Laravel Version 11`

How can I dynamically display the quantity of items from the 'item_amount' column when a product name is selected from the 'item_name' dropdown menu in Laravel 11, based on the data stored in the database? Database id item_code item ...

Comprehensive route from a one-dimensional array

I have a specific array structure that looks like this : var items = [ [1, 0, 'Apple'], [2, 1, 'Banana'], [3, 0, 'Orange'], [4, 3, 'Grape'], [5, 0, 'Cherry'], [6, 0, 'Mango'], [7, 6, 'Pear&a ...