将jQuery转换为vanilla JS - 在h1之后插入p元素

问题描述:

关于如何将此jQuery转换为vanilla JS的任何想法:

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

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

我是jQuery的新手,甚至比香草JS更新。

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

这是我得到的:

var newP = document.createElement('p');

var pTxt = document.createTextNode('This paragraph was inserted with JavaScript');

var header = document.getElementsByTagName('h1');

不知道从哪里开始?

jQuery在幕后为你做了很多。等效的纯DOM代码可能如下所示:

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);
    }
}

在行动中查看

请注意,您还可以使用 textContent / innerText 而不是创建文本节点。你试图学习如何直接操作DOM而不是让jQuery完成所有工作,这很好。理解这些东西真好,只记得jQuery和其他框架可以为你减轻这些负担:)

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