在元素的开头生成 innerHTML

generate innerHTML at the start of an element

我想在现有元素的开头生成 HTML 代码。

这是现有的 HTML-元素:

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

在我当前的解决方案中,我将生成的元素添加到现有内容下方:

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

如何在具有 innerHTML 的元素的现有内容之上添加内容?

document.getElementById('container').innerHTML 添加到作业中并删除 += shorthand:

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

此代码可能有效

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);

有一个相对较新的函数专门用于此: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>

与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>