ปรับปรุงการโพสต์ของ @Peter T โดยรวบรวมโซลูชั่นทั้งหมดเข้าด้วยกันในที่เดียว
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}";
}
การใช้XPathหาตำแหน่งขององค์ประกอบใน Tree DOM และแทรกข้อความที่ระบุที่ตำแหน่งที่ระบุใน XPath_Element ลองใช้รหัสนี้บนคอนโซลของเบราว์เซอร์
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);