Sometimes we requires in get previous sibling element in the HTML code and perform some operations in it like inserting any other element or get the innerHTML of previous element.
We can do this using 'previousElementSibling' property of JavaScript. Here is the sample HTML and JavaScript code for the same.
Get Previous Sibling HTML element :
Here is the example to insert any element in the preivous sibling HTML element -<html> <body> <div id="firstDiv"> </div> <div id="SecondDiv"> </div> <script> //this line will return the first div let firstDivEle = document.getElementById("SecondDiv").previousElementSibling; </script> </body> </html>
<html> <body> <div id="firstDiv"> </div> <div id="SecondDiv"> </div> <script> //this code will get the first div and insert button in it let firstDivEle = document.getElementById("SecondDiv").previousElementSibling; let btnToAdd = document.createElement('BUTTON'); btnToAdd.appendChild(document.createTextNode("Button")); firstDivEle.insertBefore(btnToAdd, firstDivEle.firstChild); </script> </body> </html>
Comments
Post a Comment