Создайте пользовательский элемент на месте инициализации кода - PullRequest
0 голосов
/ 03 мая 2019

Я пытаюсь создать элемент с использованием JavaScript в месте инициализации скрипта.

Мне нужно иметь возможность просто вызвать функцию, чтобы элемент появился сразу после тега <script> в моем HTML-документе.

Я попробовал этот код, но я не знаю, как на самом деле создать элемент.

function createElement() {

  var container = document.createElement('div');
	container.setAttribute("class", 'someDiv');
	document.createElement(container);
  
}
.someDiv {
  height: 100px;
  width: 100px;
  background-color: gold;
}
<body>

<script>
  createElement("div", "someDiv");
</script>

</body>

Ответы [ 4 ]

1 голос
/ 03 мая 2019

Используя document.currentScript, мы можем получить ссылку на элемент script, в котором выполняется код, а затем, используя .nextElementSibling, мы можем получить следующий узел-братэто элемент.Наконец, с .insertBefore и .appendChild() мы можем вставить новый элемент непосредственно перед тем, как элемент был передан в качестве аргумента (родственный элемент, который был найден ранее, или body, еслиничего не найдено).

ПРИМЕЧАНИЕ : Не вызывайте вашу функцию createElement, так как это может вызвать конфликт имен с document.createElement().

.элемент сразу после элемента script.

.someDiv {
  height: 100px;
  width: 100px;
  background-color: gold;
}
<head>
 <script>
   function create(type, style) {
     var container = document.createElement(type);
     container.classList.add(style);  // Best way to add a class
     container.textContent = "Hello!";

     let sibling = document.currentScript.nextElementSibling;
     if(sibling){
       // Insert the new element before the next sibling
       sibling.parentNode.insertBefore(sibling, container)
     } else {
       // Insert the new element at the end of the body
       document.body.appendChild(container);  
     }
   }
 </script>
</head>
<body>

  <p>The new element should be right below this.</p>
  <script>
    create("div", "someDiv");
  </script>
  <p>The new element should be right above this.</p>

</body>
1 голос
/ 03 мая 2019

document.currentScript, кажется, имеет хорошую поддержку браузера и даст нам элемент script, содержащий код, выполняемый в данный момент.

Если вы хотите заменить текущий script другим элементом, используйте его следующим образом:

<script>
  const replacementText = document.createTextNode("hi, I'm the replacement!");

  document.currentScript.parentNode.replaceChild(replacementText, document.currentScript);
</script>

Если вы просто хотите вставить элемент после текущего скрипта, не заменяя его :

<script>
  const newText = document.createTextNode("hi, I'm new text!");
  const currentScript = document.currentScript;

  currentScript.parentNode.insertBefore(newText, currentScript.nextSibling);
</script>

Вот более сложный пример с использованием предварительно написанного HTML:

<script>
  const currentScript = document.currentScript;
  
  const templateFragment = (function(){
    const templateEl = document.createElement("template");
    templateEl.innerHTML = `
    <ul>
      <li>Hi!</li>
      <li>I am a list!</li>
    </ul>
    `;
    
    return templateEl.content;
  })();

  currentScript.parentNode.insertBefore(templateFragment, currentScript.nextSibling);
</script>
1 голос
/ 03 мая 2019

Вы можете использовать insertBefore и целевую точку вставки в качестве скрипта следующим образом:

var script = document.querySelector('script:last-of-type');
var container = document.createElement('div');

document.body.insertBefore.insertBefore(script, container);
0 голосов
/ 03 мая 2019

Вы можете использовать .insertBefore () , чтобы добавить какой-либо элемент перед следующим sibling вашего script. Чтобы сослаться на ваш script, вы можете добавить к нему атрибут id:

.someDiv {
  height: 100px;
  width: 100px;
  background-color: gold;
}
<body>
  <p>I'm inside the body, before the script TAG</p>
  <p>New element should appear just after this text...</p>
  
  <script id="myScript">
  
    function createElement()
    {
      var container = document.createElement('div');
      container.setAttribute("class", 'someDiv');
      var script = document.getElementById("myScript");
      script.parentNode.insertBefore(container, script.nextSibling);
    }

    createElement();

  </script>

  <p>I'm inside the body, but after the script TAG</p>

</body>
...