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

224
Vistas
¿Cómo reemplazar el intervalo anidado al elemento div en JQuery?

Estoy tratando de verificar si el htmlData dado tiene elementos span rango anidados (principal, secundario, no hermanos) con data-fact nombre de atributo o no.

si es así, reemplácelo con span to div with class='inline-span' pase todos los atributos con él. de lo contrario, simplemente devuelva el htmlData

 var htmlData = `<p style="font: 10pt Times New Roman, Times, Serif; margin: 0pt 0;" xvid="f5ea22ec52553bc61525766b631e126f"> <span xvid="2b80c95cd4b851345ba4c3fe6937d30b" conceptid="619959bc062c677faebd7a6f" xbrlid="rr:ProspectusDate" class="manual-map" data-fact="619959c0062c677faebd7b55"> <span xvid="ca5635a4e4de332d7dc3036a68e57009" class="wrapped manual-map" data-fact="619959c0062c677faebd7b57">November 1, 2021</span> </span> </p> ` replaceTags(htmlData)
 function replaceTags (htmlData) { var $elm = $(htmlData).find("span[data-fact]"); var $nestedElm = $elm.children().length > 1; if($nestedElm){ htmlData = htmlData.replace(/<span/g, '<div class="inline-span" '); htmlData = htmlData.replace(/<\/span>/g, '<\/div>'); }else{ return htmlData; } },

La salida htmlData que quiero es algo como esto

 <p style="font: 10pt Times New Roman, Times, Serif; margin: 0pt 0;" xvid="f5ea22ec52553bc61525766b631e126f"> <div class='inline-span' xvid="2b80c95cd4b851345ba4c3fe6937d30b" conceptid="619959bc062c677faebd7a6f" xbrlid="rr:ProspectusDate" class="manual-map" data-fact="619959c0062c677faebd7b55"> <div class='inline-span' xvid="ca5635a4e4de332d7dc3036a68e57009" class="wrapped manual-map" data-fact="619959c0062c677faebd7b57">November 1, 2021</div> </div> </p>

Aquí no puedo encontrar si el elemento span está anidado o no y luego la conversión de cómo puedo pasar class='inline-span' con todos los atributos anteriores al div .

PD: la respuesta que quiero está en JQuery

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

0

Por lo general, es una mala idea hacer un reemplazo de cadenas para cambiar HTML. En su lugar, debe usar las herramientas de jquery para manipular el DOM. Que es más seguro y menos propenso a errores.

 const replaceTags = ($tagToReplace) => { // create a copy of the htmlData const $cloned = $tagToReplace.clone(); // While there are still more span's in the p while ($cloned.find('span[data-fact]').length > 0) { // get the next span to replace with a div const $span = $($cloned.find('span[data-fact]')[0]); // create the new div const $newDiv = $('<div>'); // copy the span's html into the div $newDiv.html($span.html()); // For each attribute in the span ... $.each($span[0].attributes, (_ , attr) => { // ... set the new div to have the span's attribute. $newDiv.attr(attr.name, attr.value); }); // new div needs 'inline-span' property. $newDiv.addClass('inline-span'); // finally replace the span with the new div $span.replaceWith($newDiv); } return $cloned; } // select tag to replace const $tagToReplace = $('p'); // get the new cloned tag const $newHtmlData = replaceTags($tagToReplace); // add the cloned to the body $('body').append($newHtmlData); // print that new elements html console.log($newHtmlData[0].outerHTML);
 p { padding: 8px; border: 1px dashed green; } span[data-fact] { border: 1px solid red; padding: 3px; } div[data-fact] { border: 1px solid blue; padding: 3px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p style="font: 10pt Times New Roman, Times, Serif; margin: 0pt 0;" xvid="f5ea22ec52553bc61525766b631e126f"> <span xvid="2b80c95cd4b851345ba4c3fe6937d30b" conceptid="619959bc062c677faebd7a6f" xbrlid="rr:ProspectusDate" class="manual-map" data-fact="619959c0062c677faebd7b55"> <span xvid="ca5635a4e4de332d7dc3036a68e57009" class="wrapped manual-map" data-fact="619959c0062c677faebd7b57">November 1, 2021</span> </span> </p>

NOTA: no es HTML válido tener una etiqueta div dentro de p , por lo que probablemente también debería reemplazar la etiqueta p .

about 4 years ago · Juan Pablo Isaza Denunciar

0

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> var htmlData = `<p style="font: 10pt Times New Roman, Times, Serif; margin: 0pt 0;" xvid="f5ea22ec52553bc61525766b631e126f"> <span xvid="2b80c95cd4b851345ba4c3fe6937d30b" conceptid="619959bc062c677faebd7a6f" xbrlid="rr:ProspectusDate" class="manual-map" data-fact="619959c0062c677faebd7b55"> <span xvid="ca5635a4e4de332d7dc3036a68e57009" class="wrapped manual-map" data-fact="619959c0062c677faebd7b57">November 1, 2021</span> </span> </p> ` console.log(replaceTags(htmlData, "span span[data-fact]","div")); //a very handy function from Matt Basta to rplace tag names cannot be done on the fly without such functions function replaceElement(source, newType) { // Create the document fragment const frag = document.createDocumentFragment(); // Fill it with what's in the source element while (source.firstChild) { frag.appendChild(source.firstChild); } // Create the new element const newElem = document.createElement(newType); // Empty the document fragment into it newElem.appendChild(frag); // Replace the source element with the new element on the page source.parentNode.replaceChild(newElem, source); } //we now use our function as warper on above function. function replaceTags (htmlData,whatToChange,withWhat) { var fragment = document.createElement('just'); fragment.innerHTML=htmlData; var found = fragment.querySelector(whatToChange); if(found){ replaceElement(fragment.querySelector(whatToChange), withWhat);} return fragment.innerHTML; } </script>

Llegar a lo que quiere aquí es una solución más lógica que combina un montón de lógicas de búsqueda para hacer el trabajo. No es perfecto pero está cerca

about 4 years ago · Juan Pablo Isaza Denunciar

0

Hice algunos cambios relacionados con Buscar en el elemento HTML y en reemplazar el código jquery aquí hay una demostración que funciona, espero que sea útil para usted.

puede reemplazar directamente todo html con me gusta

 htmlData = htmlData.replace($factElem[0].outerHTML, 'div html');

usando $factElem[0].outerHTML puede encontrar el elemento que contiene [data-fact] html. sí, puede verificar solo usando data-fact y reemplazarlo con div, no se necesita un lapso

Actualicé el código. Compruébalo ahora.

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function () { $("button").click(function () { var htmlData = '<p style="font: 10pt Times New Roman, Times, Serif; margin: 0pt 0;" xvid="f5ea22ec52553bc61525766b631e126f"><span xvid="2b80c95cd4b851345ba4c3fe6937d30b" conceptid="619959bc062c677faebd7a6f" xbrlid="rr:ProspectusDate" class="manual-map" data-fact="619959c0062c677faebd7b55"><span xvid="ca5635a4e4de332d7dc3036a68e57009" class="wrapped manual-map" data-fact="619959c0062c677faebd7b57">November 1, 2021</span></span></p>' replaceTags(htmlData); }); }); function replaceTags(htmlData) { var $factElem = $(htmlData).find('[data-fact]'); if ($factElem) { htmlData = htmlData.replace($factElem[0].outerHTML, '<div class="inline-span" xvid="2b80c95cd4b851345ba4c3fe6937d30b" conceptid="619959bc062c677faebd7a6f" xbrlid="rr:ProspectusDate" class="manual-map" data-fact="619959c0062c677faebd7b55"><div class="inline-span" xvid="ca5635a4e4de332d7dc3036a68e57009" class="wrapped manual-map" data-fact="619959c0062c677faebd7b57">November 1, 2021</div></div>'); $("#append").empty().append(htmlData); alert(htmlData); } else { $("#append").empty().append(htmlData); } } </script> </head> <body> <div id="append"></div> <button>Click me to Replace!!</button> </body> </html>

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