Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
Ignore el intervalo de separación en la selección de ventana para obtener el índice de inicio y finalización

Tengo una etiqueta html que es

 <span>This is first text<span class="ignore">Second</span> This is third text<span>

Estoy tratando de obtener el índice de inicio y final del texto seleccionado. Cuando selecciono el third , obtengo un índice de inicio y finalización como 34 39 Pero espero 27 32

Intenté el siguiente enfoque

 export const findTextRange = (element) => { if (!element) return; let start = 0, end = 0; let sel, range, priorRange, text; if (typeof window.getSelection != "undefined") { sel = window.getSelection(); text = sel + ''; if (window.getSelection().rangeCount <= 0) { return; } range = window.getSelection().getRangeAt(0); priorRange = range.cloneRange(); priorRange.selectNodeContents(element); priorRange.setEnd(range.startContainer, range.startOffset); start = priorRange.toString().length; end = start + (sel + '').length; } else if (typeof document.selection !== "undefined" && (sel = document.selection).type !== "Control") { text = sel + ''; range = sel.createRange(); priorRange = document.body.createTextRange(); priorRange.moveToElementText(element); priorRange.setEndPoint("EndToStart", range); start = priorRange.text.length; end = start + (sel + '').length; } return { start, end, text }; }

¿Hay alguna forma en la que pueda ignorar el elemento span con ignore la clase?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Guarde el HTML inicial, luego elimine todos los elementos que tengan la clase .ignore :

 const html = element.innerHTML; element.querySelectorAll('.ignore').forEach((e) => e.remove());

Después de obtener el rango, restaure el HTML original:

 element.innerHTML = html;

Retazo

 const findTextRange = (element) => { if (!element) return; const html = element.innerHTML; // store original HTML element.querySelectorAll('.ignore').forEach((e) => e.remove()); // remove ignore elements let start = 0, end = 0; let sel, range, priorRange, text; if (typeof window.getSelection != "undefined") { sel = window.getSelection(); text = sel + ''; if (window.getSelection().rangeCount <= 0) { return; } range = window.getSelection().getRangeAt(0); priorRange = range.cloneRange(); priorRange.selectNodeContents(element); priorRange.setEnd(range.startContainer, range.startOffset); start = priorRange.toString().length; end = start + (sel + '').length; } else if (typeof document.selection !== "undefined" && (sel = document.selection).type !== "Control") { text = sel + ''; range = sel.createRange(); priorRange = document.body.createTextRange(); priorRange.moveToElementText(element); priorRange.setEndPoint("EndToStart", range); start = priorRange.text.length; end = start + (sel + '').length; } element.innerHTML = html; // restore HTML console.log(start, end, text); return { start, end, text }; } document.querySelector('#P').addEventListener('click', function() {findTextRange(this)});
 <span id="P">This is first text<span class="ignore">Second</span> This is third text<span>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda