JavaScript得到父元素,并为兄弟姐妹写持有者div [英] JavaScript get parent element and write holder div for siblings

查看:96
本文介绍了JavaScript得到父元素,并为兄弟姐妹写持有者div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构:

 < div class =parent> 
< div id =child1> Content here< / div>
< div class =child2> Content here< / div>
< / div>

在onload时,我想添加一个持有人div,它保存所有父母的孩子:

 < div class =parent> 
< div id =holder>
< div id =child1> Content here< / div>
< div class =child2> Content here< / div>
< / div>
< / div>

只知道child1id,如何在自己和兄弟姐妹周围添加一个持有人div? / p>

注意事项




  • child1唯一已知的标识符。

  • 类parent和child2是动态名称,将更改,因此不能用作标识符。

  • 需要是香草JavaScript。



想法?

解决方案

看到这必须是JavaScript(而不是jQuery),你只能通过id识别child1,你可以做一些粗糙的事情:

  var child1 = document.getElementById(child1),
parent = child1.parentNode,
contents = parent.innerHTML;
parent.innerHTML ='< div id =holder>'+ contents +'< / div>';

希望这有帮助...


I have the following structure:

<div class="parent">
  <div id="child1">Content here</div>
  <div class="child2">Content here</div>
</div>

At onload, I want to include a "holder" div, that holds all the parent's children like so:

<div class="parent">
  <div id="holder">
    <div id="child1">Content here</div>
    <div class="child2">Content here</div>
  </div>
</div>

Knowing only the "child1" id, how can I add a holder div around itself and siblings?

Considerations

  • The "child1" id is the only known identifier.
  • The class "parent" and "child2" are dynamic name and will change, so can't be used as identifiers.
  • needs to be vanilla JavaScript.

Thoughts?

解决方案

Seeing as this has to be JavaScript (and not jQuery) and you can only indentify the child1 by id you could do something as crude as this:

var child1 = document.getElementById("child1"),
    parent = child1.parentNode,
    contents = parent.innerHTML ;
    parent.innerHTML = '<div id="holder">' + contents + '</div>';

Hope this helps...

这篇关于JavaScript得到父元素,并为兄弟姐妹写持有者div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆