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

88
Vistas
Javascript focus on span that is inside a div

div {
  border: 3px solid black;
}

span {
  border: 2px solid blue;
}
<div contenteditable>
  <span contenteditable id="haha"><i>asd</i></span>
</div>

I want to focus on #haha, but it only works if I move the element outside the div

div {
  border: 3px solid black;
}

span {
  border: 2px solid blue;
}
<div contenteditable>

</div>
<span contenteditable id="haha"><i>asd</i></span>

Currently using this this code for the focus, if there a way to focus on the span element even if it's inside the div?

document.querySelector(`#haha`).focus();
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Try setting tabindex="0". It allows items which normally are not focusable to receive focus

    
div {
  border: 3px solid black;
}

span {
  border: 2px solid blue;
}
span:focus{
border-color: green;
}
<div contenteditable>
  <span tabindex="0" contenteditable id="haha"><i>asd</i></span>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try document.getElementById("haha") (notice I removed the '#')

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

Source

EDIT:

Looks like manipulating the tabindex allows this to work:

myFunction = function() {

  let x = document.getElementById("haha");
  x.setAttribute('tabindex', '0');
  x.focus();
}

myFunction();
<div contenteditable>
  <span contenteditable="true" id="haha">asd</span>
</div>
<button class="bold">Bold</button>

<div contenteditable="true">
  whatever
</div>

<button class="bold">Bold</button>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to add some text into the div. Then they'll each have their own content to edit.

div[contenteditable] {
  border: 3px solid black;
}

span {
  border: 2px solid blue;
}
<div contenteditable>div<span contenteditable id="haha">span</span></div>

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