jquery 如何用脚本在其他id中添加class和id

mrwjdhj3  于 2023-01-25  发布在  jQuery
关注(0)|答案(1)|浏览(120)

我需要添加此代码

<p id="allpostwp">all</p>
<p class="showOneWP show1" target="1">A</p>
<p class="showOneWP show2" target="2">B</p>
<p class="showOneWP show3" target="3">C</p>
<p class="showOneWP show4" target="4">D</p>

在此文本内,但有脚本

<div class="wpearoption">
HTML HERE WITH SCRIPT 
</div>

结果如下代码HTML:

<div class="wpearoption">
<p id="allpostwp">all</p>
<p class="showOneWP show1" target="1">A</p>
<p class="showOneWP show2" target="2">B</p>
<p class="showOneWP show3" target="3">C</p>
<p class="showOneWP show4" target="4">D</p>
</div>
5uzkadbs

5uzkadbs1#

这样...

const
  newDiv    = document.createElement('div')
, firstNode = document.querySelector('#allpostwp')
  ;
firstNode.parentNode.insertBefore(newDiv, firstNode);

newDiv.className = 'wpearoption';

document.querySelectorAll('#allpostwp, #allpostwp ~ p.showOneWP')
  .forEach( nod => newDiv.appendChild(nod) );
<p>Blah blah bla....1</p>

<p id="allpostwp">all</p>
<p class="showOneWP show1" target="1">A</p>
<p class="showOneWP show2" target="2">B</p>
<p class="showOneWP show3" target="3">C</p>
<p class="showOneWP show4" target="4">D</p>

<p>Blah blah bla....2</p>

相关问题