Tengo este código y se ejecuta como quiero. El objetivo es encapsular el elemento ("PRUEBA") con una etiqueta en negrita . Solo quiero saber si hay algún método integrado único para encapsular el elemento por etiqueta html. algo así como insertAdjacentHTML , pero insertAdjacentHTML cerrará automáticamente la etiqueta. Entonces, en este caso, no puedo hacer 2x insertAdjacentHTML ( afterbegin para <b> y beforeend para </b>).
Puedo usar el siguiente código sin problema, solo tengo curiosidad por saber si hay una forma de encapsular el elemento.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="text" onClick=makebold()> TEST </div> <script> function makebold() { var text = document.getElementById("text").innerHTML ; text = "<b>"+text+"</b>"; document.getElementById("text").innerHTML = text; } </script> </body> </html>Puede usar document.createElement para crear un <b> , agregarlo al padre y agregarle el hijo existente inicialmente del padre.
function makebold() { const parent = document.getElementById("text"); parent.appendChild(document.createElement('b')).appendChild(parent.childNodes[0]); } <div id="text" onClick=makebold()> TEST </div> Este atajo funciona porque appendChild devuelve el nodo adjunto. Entonces parent.appendChild(document.createElement('b')) devolverá el <b> que se creó, y luego puede llamar a appendChild en ese <b> .
prueba esto. encapsular y encapsular etiqueta específica . como lo pediste
Ejecute el fragmento de código : function capsulate(tag, targetElmID) { var text = document.getElementById(targetElmID).innerText; text = "<"+tag+">"+text+"</"+tag+">"; document.getElementById(targetElmID).innerHTML = text; } function encapsulate(tag, targetElmID){ let text_ = document.getElementById(targetElmID).innerText; let newtext = ''; let p_ = false; for(let a in text_){ if(text_[a] === "<" && text_[a+1] === tag && p_ === false){ p_ = true; } else if(text_[a] === ">" && p_ === true){ p_ = false; } if( p_ === false ){ newtext += text_[a]; } } document.getElementById(targetElmID).innerHTML = newtext; } <p>Capsulate with html tag. sintax: capsulate('tagName', 'targetElementID')</p> <button onclick="capsulate('b', 'text')">capsulate with b tag</button> <p>Encapsulate specific html tag. sintax: encapsulate('tagName', 'targetElementID')</p> <button onclick="encapsulate('b', 'text')">encapsulate</button> <p>Demo : </p> <span id="text">i am the rabbit</span>, i love carrot.Utilice marco flotante. En ese caso, el contenido estará completamente aislado del documento principal.
También usar html (parsedHTML) me parecería bastante inseguro de usar.