Search code examples
javascripthtmlgoogle-chrome-extension

How do I append a div container to a specific area of a webpage?


I am asking this question because all of the other answers that I found are dealing with JQuery. I am not using JQuery, just pure JS.

Currently I create a div and add content into the div using Create Element and innerHTML. I then use appendChild on the body of the document to add the HTML to the document. The issue is that the injected HTML is at the very bottom of the body but I want it at the top.

How can I do this?

EDIT: My code:

// Content-Script Function: This function toggles the extention on and fetches the required resources from the server.
function toggleExtOn() {  
  //Get url for the html page.
  let url = chrome.runtime.getURL("flipfinder.html");
  //Create the container.
  var flipfinderContainer = document.createElement('div');
  //Set the id.
  flipfinderContainer.setAttribute("id", "flipfinderContainer");
  //Add the html to the div using iframe.
  flipfinderContainer.innerHTML = "<h1>Hello</h1>";
  //Append the div to the pages html body.
  document.body.appendChild(flipfinderContainer);
}

Solution

  • You can use the prepend function to prepend the element to your div. Prepending is like appending but it adds to the start instead of the end.

    For example:

    const element = document.createElement("img");
    document.body.prepend(element);