генерировать innerHTML в начале элемента - PullRequest
0 голосов
/ 11 июня 2018

Я хочу сгенерировать HTML-код в начале существующего элемента.

Это существующий HTML-элемент:

<div id="container">
  <p>end of the element</p>
</div>

В моем текущем решении я добавляю сгенерированный элементпод существующим содержимым:

document.getElementById(container).innerHTML += "<p>start of the element</p>";

Как добавить содержимое поверх существующего содержимого элемента с innerHTML?

Ответы [ 4 ]

0 голосов
/ 01 июля 2018

С jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
</script>
<script>
$('#container').prepend("<p>start of element</p>");
</script>

$('#addText').click(function(){
$('#container').prepend("<p>Prepended Text:"
 + $('#textToPrepend').val() +
"</p>");
});
#container{
  border: 2px solid black;
  padding: 10px;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<input type="text" id = "textToPrepend"/><br/>
<button id = "addText">Add text to div</button>
<div id = "container"><p> Div Container<p/></div>
</html>
0 голосов
/ 11 июня 2018

Этот код может работать

var newItem = document.createElement("p");
newItem.innerHTML = "start of the element";
var container = document.getElementById("container");
var currentItem = document.getElementById("container").firstChild;
container.insertBefore(newItem, currentItem);
0 голосов
/ 28 июня 2018

Для этого есть относительно новая функция: insertAdjacentHTML.Который имеет четыре варианта: перед открывающим тегом (beforeBegin), сразу после открывающего тега (afterBegin), непосредственно перед закрывающим тегом (beforeEnd) и после закрывающего тега (afterEnd).В вашем случае:

<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
</head>
<body>
    <div>
        <p>First paragraph in the code, but should become second after the Javascript fired.</p>
    </div>
    <script>
        document.querySelector('div').insertAdjacentHTML('afterBegin','<p>Second paragraph in the code, but should become first.</p>')
    </script>
</body>
</html>
0 голосов
/ 11 июня 2018

Добавьте document.getElementById('container').innerHTML к назначению и удалите += сокращение:

document.getElementById('container').innerHTML = "<p>start of the element</p>" + document.getElementById('container').innerHTML;
<div id="container">
  <p>end of the element</p>
</div>
...