在元素的开头生成innerHTML

时间:2018-06-11 09:14:51

标签: javascript html innerhtml

我想在现有元素的开头生成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 :(得分:5)

在作业前加document.getElementById('container').innerHTML并删除+=简写:

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

答案 1 :(得分:1)

特别有一个相对较新的功能:insertAdjacentHTML。其中有四个选项:在开始标记(beforeBegin之前,在开始标记(afterBegin)之后,在结束标记(beforeEnd之前)和结束标记({ {1}})。对于您的情况:

afterEnd

答案 2 :(得分:0)

此代码可能有效

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

答案 3 :(得分:0)

使用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>