Search code examples
javascripthtmlinsertadjacenthtml

encapsulate element by html tag


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>


Solution

  • 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>.