Reputation: 289
I'm trying to make an HTML page, and made an easy way to sort of creating complicated elements, which returns a DOM element. But I don't know how to append the element into the appropriate position. For example, I want to use the function in between the paragraphs in my <body>
but I don't know how.
Here is an example:
<body>
p1
<br>
p2
<br>
<script>document.getlocation().append(DOM element)</script>
<br>
p3
</body>
should yield
p1
p2
DOM element
p3
Any help is greatly appreciated, including documentations, and or code, etc.
Upvotes: 1
Views: 81
Reputation: 89224
You can use document.write
.
<body>
p1
<br>
p2
<br>
<script>document.write('<p>DOM Element</p>');</script>
<br>
p3
</body>
Upvotes: 1
Reputation: 177
I would give each of your HTML elements an id, and then proceed as in the code below. I have given you 2 example methods and links to the documentation to try. Hope that helps :)
<!DOCTYPE html>
<html>
<body>
<p id="id1">p1</p>
<br id="id2">
<p id="id3">p2</p>
<br id="id4">
<br id="id5">
<p id="id6">p3</p>
<script>
// Example 1: create element and insert before another element:
// See: https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
let newElement1 = document.createElement('p');
newElement1.innerText='New paragraph 1';
let el3 = document.getElementById('id3');
document.body.insertBefore(newElement1, el3);
// Example 2: create an element and use the insertAdjacentElement function:
// See: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement
let newElement2 = document.createElement('p');
newElement2.innerText='New paragraph 2';
let el5 = document.getElementById('id5');
el5.insertAdjacentElement('afterend', newElement2);
</script>
</body>
</html>
Upvotes: 0
Reputation: 958
After looking at your desired result, I notice multiple mistakes in your code. First of all, DOM element
must be enclosed in quotes, single or double, to treat it as a string.
Second, document.getlocation()
is not a function. What you actually need to do to place 'DOM element'
at the location where the script is being called it to use document.write()
.
<body>
p1
<br>
p2
<br>
<script>document.write('DOM element');</script>
<br>
p3
</body>
This would successfully give the desired output. Similar to echo
in PHP, document.write()
can be used to write data to the document where the script is called.
Upvotes: 1
Reputation: 15665
you need to create a tag in your html where you want to insert the element or text. Grab it and then either change the innerHTML or append children. if the latter you may want to use a p or div tag instead of span.
var sp = document.getElementById('here');
sp.style.display='block';
sp.innerHTML='DOM Element';
<body>
p1
<br>
p2
<br>
<span id='here'></span>
p3
</body>
Upvotes: 1