将具有相同类名的所有元素的innerHTML插入多个其他元素

时间:2019-06-30 10:10:30

标签: javascript html

我有一些元素具有相同的类名,我将它们的innerHTML插入另一个具有类名“ show”的元素中。预期产量

<p class="show">
  <i>1</i>
  <i>2</i>
  <i>3</i>
  <i>4</i>
  <i>5</i>
</p>

这是我的代码段;

var source = Array.from(document.getElementsByClassName("source"))
var show = document.getElementsByClassName("show")[0];

show.innerHTML = source.reduce((a, el) => a += el.textContent, '')
.show{
  display:block;
}
<span class="source">1</span>
<span class="source">2</span>
<span class="source">3</span>
<span class="source">4</span>
<span class="source">5</span>

<p class="show"></p>

3 个答案:

答案 0 :(得分:1)

我将选择所有span,然后将它们与show插入appendChild

const show = document.querySelector('.show');
document.querySelectorAll('.source')
  .forEach(span => show.appendChild(span));
console.log(show.innerHTML);
.show{
  display:block;
}
<span class="source">1</span>
<span class="source">2</span>
<span class="source">3</span>
<span class="source">4</span>
<span class="source">5</span>

<p class="show"></p>

如果您还想删除类名,则在添加时执行以下操作:

const show = document.querySelector('.show');
document.querySelectorAll('.source')
  .forEach(span => {
    show.className = '';
    show.appendChild(span)
  });
console.log(show.innerHTML);
.show{
  display:block;
}
<span class="source">1</span>
<span class="source">2</span>
<span class="source">3</span>
<span class="source">4</span>
<span class="source">5</span>

<p class="show"></p>

如果您还想更改标签名称,请提取原始元素的textContent,附加新元素,然后删除旧元素:

const show = document.querySelector('.show');
document.querySelectorAll('.source')
  .forEach(span => {
    const i = show.appendChild(document.createElement('i'));
    i.textContent = span.textContent;
    span.remove();
  });
console.log(show.innerHTML);
.show{
  display:block;
}
<span class="source">1</span>
<span class="source">2</span>
<span class="source">3</span>
<span class="source">4</span>
<span class="source">5</span>

<p class="show"></p>

答案 1 :(得分:1)

简便的解决方案:

var source = Array.from(document.getElementsByClassName("source"));
for(i=0;i<source.length;i++){
var x=document.querySelector(".show");
var element=document.createElement("i");
element.innerHTML=source[i].innerHTML;
x.appendChild(element);
}

答案 2 :(得分:0)

例如这样的

var source = Array.from(document.getElementsByClassName("source"));
var show = document.getElementById("show");
show.innerHTML = source.reduce((a, el) =>  a += '<p>' + el.innerHTML + '</p>', '');

P.S我正在按id获取源元素,因为它是单数形式,没有按类获取它的意义。

<p id="show"></p>

https://jsbin.com/hoxagih/4/edit?html,css,js,output