Javascript 如何在.js文件中加载html元素

Javascript 如何在.js文件中加载html元素,javascript,html,web,Javascript,Html,Web,我想知道如何将HTMl元素加载到可以使用HTMLDOM修改的.js文件中 像这样 var para = document.createElement("p"); 但是我不想创建一个元素,而是想得到一个已经存在的元素,但是这不可能直接将它放在一个.js文件中,因为它是html,使用纯文本编写它是一件痛苦的事情 我为什么要这样做?我想为我的所有页面创建一个通用标题栏,我不想不断更新每个页面,所以我使用了一个通用的.js脚本,每个页面都使用它,你可以使用.querySelecto

我想知道如何将HTMl元素加载到可以使用HTMLDOM修改的.js文件中 像这样

var para = document.createElement("p");
但是我不想创建一个元素,而是想得到一个已经存在的元素,但是这不可能直接将它放在一个.js文件中,因为它是html,使用纯文本编写它是一件痛苦的事情


我为什么要这样做?我想为我的所有页面创建一个通用标题栏,我不想不断更新每个页面,所以我使用了一个通用的.js脚本,每个页面都使用它,你可以使用
.querySelector()
,并给它一个类似CSS的选择器。 例如:

const myElement=document.querySelector('.element_to_select')//注意点,它非常重要

函数includeHTML(){
var z,i,elmnt,file,xhttp;
/*循环浏览所有HTML元素的集合:*/
z=document.getElementsByTagName(“*”);
对于(i=0;i


也许
document.querySelector('p#header')
为什么不使用html包含。
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>