Weatherby Syriux
Weatherby Syriux

Reputation: 51

How to load html element in .js file

I want to know how to load an HTMl element into a .js file that I can modify using HTML DOM Like this

var para = document.createElement("p");

But instead of creating an element I want to get an already existing element, but this isn't possible to put it directly in a .js file because it's html, and it's a pain to write it using plain text

Why do I want to do this? Well I want to make a universal header bar for all my pages and I don't want to keep updating each one of them so I'm using a universal .js script which every page uses

Upvotes: 0

Views: 1358

Answers (2)

Gustavo Shigueo
Gustavo Shigueo

Reputation: 501

You can use .querySelector() and give it a CSS-like selector. Example:

const myElement = document.querySelector('.element_to_select') // Notice the dot, it's really important
<p class="element_to_select"></p>

Upvotes: 1

Michael Mano
Michael Mano

Reputation: 3440

function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("include-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("w3-include-html");
          includeHTML();
        }
      }      
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
};
<div include-html="h1.html"></div> 
<div include-html="content.html"></div> 

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_html_include_2

Upvotes: 0

Related Questions