最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript InsertBefore - in a different div both within a parent div - Stack Overflow

programmeradmin2浏览0评论

I would like to insert an hr element in a different child div (2 child divs within a parent div), as per the set-up below. The insertbefore method works fine for an element within the same div but not for elements in the other child div (see code below). Is there a different method I can use to achieve this or do I want the impossible?

<body>

<div id="whole section">

<div id="group_a">
<h3 id="event_1">Heading 1</h3>    
<p> some text </p>

**// I would like to insert an hr element here**

<h3 id="event_2">Heading 2</h3>
<p> more text </p>

</div>

<div id="group_b">

**// I can only insert code here though**

<script type="text/javascript">
function add_hr(){
  var new_hr = document.createElement('hr');
  var reference = document.getElementById('event_2');
  document.body.insertBefore(new_hr, reference);
}

window.onload = function(){add_hr();};

</script>

</div>
</div>

</body>

I would like to insert an hr element in a different child div (2 child divs within a parent div), as per the set-up below. The insertbefore method works fine for an element within the same div but not for elements in the other child div (see code below). Is there a different method I can use to achieve this or do I want the impossible?

<body>

<div id="whole section">

<div id="group_a">
<h3 id="event_1">Heading 1</h3>    
<p> some text </p>

**// I would like to insert an hr element here**

<h3 id="event_2">Heading 2</h3>
<p> more text </p>

</div>

<div id="group_b">

**// I can only insert code here though**

<script type="text/javascript">
function add_hr(){
  var new_hr = document.createElement('hr');
  var reference = document.getElementById('event_2');
  document.body.insertBefore(new_hr, reference);
}

window.onload = function(){add_hr();};

</script>

</div>
</div>

</body>
Share Improve this question asked Feb 25, 2013 at 23:02 RonelzRonelz 3031 gold badge4 silver badges8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

insertBefore requires that the reference element be a direct child of the element on which you call it. Your line

document.body.insertBefore(new_hr, reference);

...tells the browser to insert new_hr before the reference element directly contained by document.body. But document.body doesn't directly contain the reference element, it's inside a div. So you get an error, because the reference element can't be found directly inside the element you're inserting into.

You can fix that by using the reference element's parent:

reference.parentNode.insertBefore(new_hr, reference);

Live Example | Source

发布评论

评论列表(0)

  1. 暂无评论