createElement()
and insertBefore()
are two JavaScript methods used to add new HTML elements in the web page, these elements are created dynamically in memory and added by JavaScript.
createElement(tagName)
creates in memory an HTML element of the tag specified by tagName.
var elm = document.createElement('div'); elm.setAttribute('class', 'o_clasa') elm.innerHTML ='Text in div tag'; console.log(elm);- This code will create in memory an object that contains the fallowing HTML code:
appendChild()
method.body
.
var elm = document.createElement('div'); elm.setAttribute('class', 'o_clasa') elm.innerHTML ='Div created with createElement(), and added with appendChild()'; document.body.appendChild(elm);
insertBefore()
adds a child node in front of another child, both inside a parent element.<h4>Example with insertBefore()</h4> <p>If you click the button, it adds a H3 tag created with createElement(), before a DIV with id='rpr'.</p> <button id='btn1'>Add H3</button> <div id='rpr'>#rpr, reper.</div> <script> function add_h3(){ // creates a H3 element, class and html content var elm = document.createElement('h3'); elm.className ='o_clasa'; elm.innerHTML = 'The <b>html text</b> content'; //gets the reference tag var reper = document.getElementById('rpr'); //adds the new element before reper (in parent body) document.body.insertBefore(elm, reper); } document.getElementById('btn1').addEventListener('click', add_h3); </script>
<h4>Example adding with insertBefore() input fields in form</h4> <p>When you click on the 'Add Box' button, the add_input() function creates and adds a text field in form.</p> <form action='#'> <input type='text' name='nume[]' /> <input type='submit' value='Submit' id='submit' /><br><br> <input type='button' value='Add box' onclick='add_input()' /> </form> <script> // creates an input element and adds it before the Submit button function add_input() { // sets a new input element, having the attributes: type=text si name=nume[] var elm = document.createElement('input'); elm.setAttribute('type', 'text'); elm.setAttribute('name', 'nume[]'); elm.style.display = 'block'; // sets css style display:block; // sets the objects for reference and parent var reper = document.getElementById('submit'); var parinte = reper.parentNode; // Adds elm parinte.insertBefore(elm, reper); } </script>
<object type="application/x-shockwave-flash" data="file.swf" width="500" height="250"> <param name="src" value="file.swf" /> Your browser not support SWF. </object>
input:focus { background-color: #88fe88; }
var jsnstr = '{"url": "http://coursesweb.net/", "title": "Web Development Courses"}'; var obj = JSON.parse(jsnstr); alert(obj.url);
if (file_put_contents("file.txt", "content")) echo "The file was created"; else echo "The file can not be created";