jQuery does a lot for you behind the scenes. Similar simple DOM code might look something like this:
// Get all header elements var header = document.getElementsByTagName('h1'), parent, newP, text; // Loop through the elements for (var i=0, m = header.length; i < m; i++) { parent = header[i].parentNode; // Check for "section" in the parent classname if (/(?:^|\s)section(?:\s|$)/i.test(parent.className)) { newP = document.createElement("p"); text = document.createTextNode('This paragraph was inserted with JavaScript'); newP.appendChild(text); // Insert the new P element after the header element in its parent node parent.insertBefore(newP, header[i].nextSibling); } }
Look in action
Note that you can also use textContent / innerText instead of creating text node. Good thing you are trying to learn how to directly manipulate the DOM, and not just let jQuery do all the work. It's nice to understand this stuff, just remember that jQuery and other frameworks are designed to lighten these loads for you :)
source share