Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
Cómo saber si un texto seleccionado está rodeado por un elemento html de no

Estoy implementando un editor de texto simple con div editable de contenido y dos botones, uno para texto en negrita y otro para cursiva. La forma en que pongo un texto en negrita o cursiva es insertando un span alrededor del texto seleccionado con class text-bold y text-italic , respectivamente, y luego hago los estilos usando css. Sin embargo, no quiero seguir agregando span dentro de un span para hacer un texto en negrita y cursiva como

 <span class="text-bold"> <span class="text-italic">Some Text</span> </span>

pero más bien, cuando selecciono un texto, quiero verificar si ya está rodeado por un span y, en caso afirmativo, agregarle una clase para reflejar el cambio deseado. Por ejemplo, supongamos que ya tengo

 <p>Hello there <span class="text-bold"> Some Text </span> </p>

en el DOM. Más tarde, si quiero hacer Some Text en cursiva, solo agrego la clase text-italic así

 <p>Hello there <span class="text-bold text-italic"> Some Text </span> </p>

Sé que selection.anchorNode.parentNode devolverá la etiqueta p que contiene, y selection.anchorOffset devolverá el desplazamiento de p en caracteres. Pero no estoy seguro de cómo usar estos datos para devolver el span circundante.

Entonces, mi pregunta es: ¿cómo puedo devolver el elemento html circundante con sus atributos si existe un texto seleccionado?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Prueba lo siguiente:

 .getSelection().getRangeAt(0).startContainer.nodeName
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!