shay levi
shay levi

Reputation: 319

Put element inside innerHTML of other element

I am writing a small editor in JavaScript. What i am asking is when I click on the 'Bold' button I add it like this:

function addBold() {
    var el = selection().anchorNode.parentNode; 
    var str = el.innerHTML; 
    var offset = selection().getRangeAt(0).endOffset;
    var start = str.substr(0,offset);
    var end = str.substr(offset, str.length);
    el.innerHTML = start + '<b>&#32;</b>' + end;
    placeCaretAtNode(el.children[0]);
}

I need to append the Bold element using appendChild in order to hold the element instead of:

el.innerHTML = start + 'HERE I NEED TO GET THIS ELEMENT' + end;

Thanks.

Upvotes: 0

Views: 416

Answers (2)

Anobik
Anobik

Reputation: 4899

Heres a code. tell me if this works

     <!DOCTYPE html>
<html>
<head>
    <script>

function  bgchange() {
try{
var child = document.createElement("b");
child.innerHTML = "Test";
document.getElementById("dvPercentage").innerHTML = document.getElementById("dvPercentage").innerHTML + "Test"
 document.getElementById("dvPercentage").appendChild(child);
 document.getElementById("dvPercentage").innerHTML = document.getElementById("dvPercentage").innerHTML + "Test"
 }catch(e){
 alert(e);
 }
};
    </script>
<head>
<body onload="bgchange()" style="background-color:red">
      <div id="dvPercentage" style="height: 80%">
</body>
</html>

So without doing el.innerHTML = start + '<b>&#32;</b>' + end;

you can go for el.appendChild(child).

Please let me know if it works

Upvotes: 1

frogatto
frogatto

Reputation: 29287

if you want to toggle bold capability you can execute the following code:

document.execCommand('bold');

But if you like your own approach try this:

var bold;

while(el.firstChild) {  // empty the el element
    el.removeChild(el.firstChild);
}

el.appendChild(document.createTextNode(start));

bold = document.createElement('b');
bold.appendchild(document.createTextNode('bold string'));
el.appendChild(bold);

el.appendChild(document.createTextNode(end));

Upvotes: 0

Related Questions