Adding div element to body or document in JavaScript

后端 未结 9 2137
醉梦人生
醉梦人生 2020-11-27 14:14

I am creating a light box in pure JavaScript. For that I am making an overlay. I want to add this overlay to body but I also want to keep the content on the page. My current

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 14:28

    improving the post of @Peter T, by gathering all solutions together at one place.

    Element.insertAdjacentHTML()

    function myFunction() {
        window.document.body.insertAdjacentHTML( 'afterbegin', '
    With some data...
    ' ); } 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 insert the specified text at a specified position to an XPath_Element. try this code over 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 = '
    Hi My name is \"YASHWANTH\"
    '; var position = 'beforeend'; insertHTML_ByXPath(xpath_DOMElement, position, childHTML);

提交回复
热议问题