improving @Peter T's post by bringing all the solutions together in one place.
Element.insertAdjacentHTML ()
function myFunction() { window.document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID" style="color:blue;"> With some data...</div>' ); } function addElement(){ var elemDiv = document.createElement('div'); elemDiv.style.cssText = 'width:100%;height:10%;background:rgb(192,192,192);'; elemDiv.innerHTML = 'Added element with some data'; window.document.body.insertBefore(elemDiv, window.document.body.firstChild); // document.body.appendChild(elemDiv); // appends last of that element } function addCSS() { window.document.getElementsByTagName("style")[0].innerHTML += ".mycss {text-align:center}"; }
Using XPath , find the position of the element in the DOM tree and paste the specified text at the specified position in XPath_Element. try this code through your browser console.
function insertHTML_ByXPath( xpath, position, newElement) { var element = document.evaluate(xpath, window.document, null, 9, null ).singleNodeValue; element.insertAdjacentHTML(position, newElement); element.style='border:3px solid orange'; } var xpath_DOMElement = '//*[@id="answer-33669996"]/table/tbody/tr[1]/td[2]/div'; var childHTML = '<div id="Yash">Hi My name is <B>\"YASHWANTH\"</B></div>'; var position = 'beforeend'; insertHTML_ByXPath(xpath_DOMElement, position, childHTML);
Yash Nov 12 '15 at 11:04 2015-11-12 11:04
source share