javascript - how to get div inside another div by calling document.getElementbyId - Stack Overflow

<div id = "a" > <div><div id ="b">child<div>so i h

<div id = "a" >   </div>
<div id ="b">  child  </div>

so i have go two div's here i want to get div"b" inside div"a" if i type:

document.getElementById("a").innerHTML =  document.getElementById("b").value;

it will give me this output

<div id = "a" > child  </div>

but what i want is

<div id = "a" >  <div id ="b">  child  </div> </div>
<div id = "a" >   </div>
<div id ="b">  child  </div>

so i have go two div's here i want to get div"b" inside div"a" if i type:

document.getElementById("a").innerHTML =  document.getElementById("b").value;

it will give me this output

<div id = "a" > child  </div>

but what i want is

<div id = "a" >  <div id ="b">  child  </div> </div>
Share Improve this question asked Jun 27, 2017 at 20:03 Ng21Ng21 2312 gold badges4 silver badges11 bronze badges 2
  • 1 BTW value is not a valid attribute for div. Maybe you meant innerHTML? – Andrew Li Commented Jun 27, 2017 at 20:05
  • yes exactly buddy you are right – Ng21 Commented Jun 27, 2017 at 20:11
Add a ment  | 

4 Answers 4

Reset to default 6

Try appendChild();

document.getElementById('a').appendChild(document.getElementById('b'));
<div id = "a" ></div>
<div id ="b">child</div>

Use element's outerHTML as follows:

document.getElementById("a").innerHTML = document.getElementById("b").outerHTML;

In the time it took me to write this, other answers were made saying the same.

Run the snippet to see the code in action...

setTimeout(function() {
  var a = document.getElementById("a");
  var b = document.getElementById("b");
  a.appendChild(b)
}, 1000)
.border {
  border: 1px solid black;
  width: 100%;
  max-width: 50px;
  text-align: center;
  margin: 5px 0;
}

.border div{
 width: 80%;
 margin: 5px auto;
}
<div id="a" class="border">A</div>
<div id="b" class="border">B</div>

You can copy the tag b to tag a copying it outerHTML

document.getElementById("a").innerHTML =  document.getElementById("b").outerHTML;

Then if you want to remove the b tag use

document.getElementById('b').remove();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744158756a4560990.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信