I want to generate HTML-code at the beginning of an existing element.
This is the existing HTML-element:
<div id="container">
<p>end of the element</p>
</div>
With my current solution I add the generated element beneath the existing content:
document.getElementById(container).innerHTML += "<p>start of the element</p>";
How to add content above the existing content of an element with innerHTML
?
I want to generate HTML-code at the beginning of an existing element.
This is the existing HTML-element:
<div id="container">
<p>end of the element</p>
</div>
With my current solution I add the generated element beneath the existing content:
document.getElementById(container).innerHTML += "<p>start of the element</p>";
How to add content above the existing content of an element with innerHTML
?
-
document.getElementById(container).innerHTML = "<p>start of the element</p>" + document.getElementById(container).innerHTML;
– Nikhil Aggarwal Commented Jun 11, 2018 at 9:16
4 Answers
Reset to default 6Prepend document.getElementById('container').innerHTML
to the assignment and remove +=
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>
There is a relatively new function especially for that: insertAdjacentHTML
. Which has four options: before the opening tag (beforeBegin
), right after the opening tag (afterBegin
), just before the closing tag (beforeEnd
), and after the closing tag (afterEnd
). In your case:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<div>
<p>First paragraph in the code, but should bee second after the Javascript fired.</p>
</div>
<script>
document.querySelector('div').insertAdjacentHTML('afterBegin','<p>Second paragraph in the code, but should bee first.</p>')
</script>
</body>
</html>
This code might work
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);
With jQuery:
<script src="https://ajax.googleapis./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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textToPrepend" /><br/>
<button id="addText">Add text to div</button>
<div id="container">
<p> Div Container
<p/>
</div>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744188182a4562306.html
评论列表(0条)