insertAdjacentHTML()
is an useful JavaScript function that can be used to insert HTML content at a specified position into DOM tree.
This function does not reparse the element it is being used on, and thus it does not corrupt the existing elements inside the element. This make it much faster than direct innerHTML
manipulation.
<h4>Example insertAdjacentHTML() - beforebegin</h4> <div id='dv1'>Div - https://coursesweb.net/</div> <p>If you click the following button, it adds a HTML content in page, with the <b>'beforebegin'</b> argument, relative to the Div above.</p> <button id='btn1'>Try it</button> <script> var cnt = '<b>Website:</b>'; var elm = document.getElementById('dv1'); document.getElementById('btn1').addEventListener('click', (ev)=>{ elm.insertAdjacentHTML('beforebegin', cnt); }); </script>
<h4>Example insertAdjacentHTML() - afterend</h4> <div id='dv1'>Div - https://coursesweb.net/</div> <p>If you click the following button, it adds a HTML content in page, with the <b>'afterend'</b> argument, relative to the Div above.</p> <button id='btn1'>Try it</button> <script> var cnt = '<b>Website:</b>'; var elm = document.getElementById('dv1'); document.getElementById('btn1').addEventListener('click', (ev)=>{ elm.insertAdjacentHTML('afterend', cnt); }); </script>
<h4>Example insertAdjacentHTML() - afterbegin</h4> <div id='dv1'>Div - Javascript insertAdjacentHTML</div> <p>If you click the following button, it adds a HTML content in page, with the <b>'afterbegin'</b> argument, relative to the Div above.</p> <button id='btn1'>Try it</button> <script> var cnt = '<b>Tutorial: </b>'; var elm = document.getElementById('dv1'); document.getElementById('btn1').addEventListener('click', (ev)=>{ elm.insertAdjacentHTML('afterbegin', cnt); }); </script>
<h4>Example insertAdjacentHTML() - beforeend</h4> <div id='dv1'>Div - Javascript insertAdjacentHTML</div> <p>If you click the following button, it adds a HTML content in page, with the <b>'beforeend'</b> argument, relative to the Div above.</p> <button id='btn1'>Try it</button> <script> var cnt = '<b>Tutorial: </b>'; var elm = document.getElementById('dv1'); document.getElementById('btn1').addEventListener('click', (ev)=>{ elm.insertAdjacentHTML('beforeend', cnt); }); </script>
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net