First, you need to hard-code an element (div
) where you want to insert a code.
Now, you need to visualize the position names. Here how it works:
<!-- beforebegin -->
<div>
<!-- afterbegin -->
foo
<!-- beforeend -->
</div>
<!-- afterend -->
Now, you can insert the code relative to the div
element. Here's a quick example:
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>
Security Considerations
When inserting HTML into a page by using insertAdjacentHTML be careful not to >use user input that hasn't been escaped.
It is recommended you not use insertAdjacentHTML when inserting plain text; >instead, use the node.textContent property or node.insertAdjacentText() method. >This doesn't interpret the passed content as HTML, but instead inserts it as >raw text.
Traditional Method
Simply, select a div and use innerHTML
property. Here's a quick example:
if(pageStatus === 'online'){
document.getElementById('insertHere').innerHTML = '<p>Server is online</p>';
}
Putting it all together:
var pageStatus = 'online';
if(pageStatus === 'online') {
document.getElementById('test').innerHTML = "<a href=\"http://www.example.com\">Goto Website</a>";
// Since, HTML attribute doesn't support single quotes, '\' is used to escape the double quotes.
} else {
document.getElementById('test').innerText = 'You can\'t proceed because page is currently offline';
}
<div id="test"></div>
Learn more about escaping the characters: What does it mean to escape a string?