Turn jQuery into vanilla JS - Insert p element after h1

Any ideas on how I will convert this jQuery to vanilla JS:

$('.section > h1').after('<p>This paragraph was inserted with jQuery</p>'); 

I am new to jQuery and even new to vanilla JS.

This, as I understand it:

 var newP = document.createElement('p'); var pTxt = document.createTextNode('This paragraph was inserted with JavaScript'); var header = document.getElementsByTagName('h1'); 

Not sure where to go from here?

+5
source share
4 answers

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 :)

+4
source

You may find this feature useful (I have not tested)

 function insertAfter(node, referenceNode) { referenceNode.parentNode.insertBefore(node, referenceNode.nextSibling); } 
+2
source

Oh it's not so bad ...

 var h1s = document.getElementsByTagName('h1'); for (var i=0, l=h1s.length; i<l; i++) { var h1 = h1s[i], parent = h1.parentNode; if (parent.className.match(/\bsection\b/i)) { var p = document.createElement('p'); p.innerHTML = 'This paragraph was inserted with JavaScript'; parent.insertBefore(p, h1.nextSibling); } } 
+1
source

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

 document.querySelectorAll('.section > h1').forEach((headline) => { headline.insertAdjacentHTML('afterend', '<p>This paragraph was inserted with jQuery</p>'); }) 
0
source

All Articles