Sunday 30 September 2018

JavaScript: insertBefore: Insert element before an element

‘insertBefore’ method is used to insert an element before given element.

Syntax
parentElement.insertBefore(newElement, targetElement);

Above statement insert newElement before targetElement.

process.js
function addData(){
 var para = document.createElement("p");
 var text = document.getElementById("text").value;
 var textNode = document.createTextNode(text);
 para.appendChild(textNode);
 
 var targetElement = document.getElementById("welcomeMsg");
 
 var div = document.getElementById("data1");
 div.insertBefore(para, targetElement);
}

changeDom.html

<!DOCTYPE html>

<html>

<head>
    <title>Change DOM</title>
    <script src="process.js"></script>
</head>

<body>

    <div id="data1">
        <input type="text" id="text" />
        <br />
        <input type="button" id="welcomeMsg" value="click me" onclick="addData();" />

    </div>
</body>

</html>


Previous                                                 Next                                                 Home

No comments:

Post a Comment