Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

360
Vistas
Why does insertBefore work weirdly with the span element?

I am trying to add a span element before a referenced span element. However, there seems to be no space between the new element and the referenced span element.

enter image description here

// Create a new, plain <span> element
let sp1 = document.createElement("span");

// Set class attribute and value
sp1.setAttribute("class", "new-element");

// Write content to element
sp1.innerText = "foo bar";
// Get the reference element
let sp2 = document.querySelector(".third-element");

// Get the parent element
let parentDiv = sp2.parentNode;

// Insert the new element into before sp2
parentDiv.insertBefore(sp1, sp2);
<div id="main-container">
    <span>foo bar</span>
    <span>foo bar</span>
    <span class="third-element">foo bar</span>
    <span>foo bar</span>
</div>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In your HTML, you have a line break after each span element which ends up being turned into a space character (technically not a space character, but the browser shows it to you this way). When you add a span with javascript, it gets inserted inline like this:

<span>new element</span><span>existing element</span>

When spans are inline with no line break, the browser does not render that magic space character. The easiest fix for this is to add some margin-right with CSS, or to just to append a space character to the text in your spans like so:

<span>This is my text </span>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda