Phyo Thiha
Phyo Thiha

Reputation: 47

The gap between input and label is not same as original DOM element when I create an element in Javascript

I'm creating li element with his children input and label element and append li to the ul element when I click the button. The gap between created input and label element is not same as the element which is already created with html.

The gap between created input and label element

enter image description here

add.addEventListener('click', function() {
   let li = document.createElement('li');
   
   let input = document.createElement('input');
   input.type = 'checkbox';
				
   let label = document.createElement('label');
   label.textContent = text.value;

   li.appendChild(input);
   li.appendChild(label);

   characters.appendChild(li);
});
<ul id="characters">
 <li>
   <input type="checkbox">
   <label>Mickey</label>
 </li>
</ul>

<input type="text" id="text">
<input type="submit" value="add" id="add">

Upvotes: 2

Views: 86

Answers (1)

K&#233;vin Bibollet
K&#233;vin Bibollet

Reputation: 3623

This gap exists because how the way is written your HTML source. The line break is taken into account here, and sometimes produce a space when met:

<input type="checkbox"> // LINE BREAK HERE
<label>Mickey</label>

An live example below:

<ul id="characters">
 <li>
   <input type="checkbox"><label>Without line return</label>
 </li>
 <li>
   <input type="checkbox">
   <label>With line return</label>
 </li>
</ul>

I guess you want to keep the line break version for your source. In that case, add a text node between your two HTML tags:

const add = document.querySelector('#add');

add.addEventListener('click', function() {
   let li = document.createElement('li');

   let input = document.createElement('input');
   input.type = 'checkbox';

   let label = document.createElement('label');
   label.innerText = text.value;

   li.appendChild(input);
   li.appendChild(document.createTextNode('\n'));
   li.appendChild(label);

   characters.appendChild(li);
});
<ul id="characters">
 <li>
   <input type="checkbox">
   <label>Mickey</label>
 </li>
</ul>

<input type="text" id="text">
<input type="submit" value="add" id="add">

Or, there is also a quiet old trick which consists to comment your line breaks:

const add = document.querySelector('#add');

add.addEventListener('click', function() {
   let li = document.createElement('li');

   let input = document.createElement('input');
   input.type = 'checkbox';

   let label = document.createElement('label');
   label.innerText = text.value;

   li.appendChild(input);
   li.appendChild(label);

   characters.appendChild(li);
});
<ul id="characters">
 <li>
   <input type="checkbox"><!--
   --><label>Mickey</label>
 </li>
</ul>

<input type="text" id="text">
<input type="submit" value="add" id="add">

Upvotes: 2

Related Questions