可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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 :)
回答2:
You might find this function useful (I didn't test)
function insertAfter(node, referenceNode) { referenceNode.parentNode.insertBefore(node, referenceNode.nextSibling); }
回答3:
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); } }