Turn jQuery into vanilla JS - Insert p element after h1

匿名 (未验证) 提交于 2019-12-03 01:22:02

问题:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!