Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn jQuery into vanilla JS - Insert p element after h1

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

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

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

This is as far as I got:

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?

like image 556
RyanP13 Avatar asked Aug 09 '10 23:08

RyanP13


1 Answers

jQuery does a lot for you behind the scenes. The equivalent plain 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's 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);
    }
}

See it in action

Note that you can also use textContent/innerText instead of creating the text node. It's good that you're trying to learn how to directly manipulate the DOM rather than just letting jQuery do all the work. It's nice to understand this stuff, just remember that jQuery and other frameworks are there to lighten these loads for you :)

like image 185
Andy E Avatar answered Oct 30 '22 19:10

Andy E