如何将一个div的值写入另一个div

时间:2019-06-22 12:22:27

标签: javascript html

我有以下HTML,我想将值从一个div拖到另一个div中,并在可能的位置之间插入一个:

即将把div class="ITSv"的值添加到div class="ITSn"的值

源HTML:

<div id="HTML_SPEC"
 class="ITSs">
<div class="ITSg">Specifications</div>
<div class="ITSr0">
    <div class="ITSn">Battery form</div> 
    <div class="ITSv">Cylinder</div>
</div>
<div class="ITSg">Batterie</div>
<div class="ITSr0">
    <div class="ITSn">battery voltage</div> 
    <div class="ITSv">1,5 V</div>
</div>
<div class="ITSr1">
    <div class="ITSn">Capacity</div> 
    <div class="ITSv">7800 mAh</div>
</div>

目标格式:

<div id="HTML_SPEC"
 class="ITSs">
<div class="ITSg">Specifications</div>
<div class="ITSr0">
    <div class="ITSn">Batteryform: Cylinder</div> 
</div>
<div class="ITSg">Batterie</div>
<div class="ITSr0">
    <div class="ITSn">battery voltage: 1,5 V</div> 
</div>
<div class="ITSr1">
    <div class="ITSn">Capacity: 7800 mAh</div> 
</div>

2 个答案:

答案 0 :(得分:3)

您可以执行以下操作

  

Array.from(document.getElementsByClassName('ITSn')).forEach(element => {
element.innerText += ': ' + element.nextElementSibling.innerText;
   element.nextElementSibling.remove();
});
<div id="HTML_SPEC"
 class="ITSs">
<div class="ITSg">Specifications</div>
<div class="ITSr0">
    <div class="ITSn">Battery form</div> 
    <div class="ITSv">Cylinder</div>
</div>
<div class="ITSg">Batterie</div>
<div class="ITSr0">
    <div class="ITSn">battery voltage</div> 
    <div class="ITSv">1,5 V</div>
</div>
<div class="ITSr1">
    <div class="ITSn">Capacity</div> 
    <div class="ITSv">7800 mAh</div>
</div>

答案 1 :(得分:2)

不需要Js 。只需尝试使用CSS display属性after伪元素

.ITSn:after {
  content: ': '
}

.ITSn,
.ITSv {
  display: inline-block;
}
<div id="HTML_SPEC" class="ITSs">
  <div class="ITSg">Specifications</div>
  <div class="ITSr0">
    <div class="ITSn">Battery form</div>
    <div class="ITSv">Cylinder</div>
  </div>
  <div class="ITSg">Batterie</div>
  <div class="ITSr0">
    <div class="ITSn">battery voltage</div>
    <div class="ITSv">1,5 V</div>
  </div>
  <div class="ITSr1">
    <div class="ITSn">Capacity</div>
    <div class="ITSv">7800 mAh</div>
  </div>
</div>