1

I have this code and it runs as i want. The goal is to encapsulate the element ("TEST") with bold tag . I just want to know if there any single builtin method to encapsulate element by html tag? something like insertAdjacentHTML , but the insertAdjacentHTML will automatically close the tag. So in this case i can't do 2x insertAdjacentHTML (afterbegin for <b> and beforeend for the </b>).

I can use the code below with no problem, i'm just curious if there is way to encapsulate element.

<!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>
andio
  • 1,574
  • 9
  • 26
  • 45

3 Answers3

1

You can use document.createElement to create a <b>, append it to the parent, and append the parent's initially existing child to it.

function makebold() {
  const parent = document.getElementById("text");
  parent.appendChild(document.createElement('b')).appendChild(parent.childNodes[0]);
}
<div id="text" onClick=makebold()>
  TEST
</div>

This shortcut works because appendChild returns the appended node. So parent.appendChild(document.createElement('b')) will return the <b> that's created, and then you can call appendChild on that <b>.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

try this. capsulate and encapsulate specific tag. as your request

Run the code snippet :

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.
Hanna Rose
  • 412
  • 2
  • 9
0

Use iframe. In that case the contents will be fully isolated from the main document.

Also using html(parsedHTML) would look quite insecure to me to use.