admin管理员组

文章数量:1432752

Here i want to remove a last div of body as highlighted in image. I have tried with jqyery $('body :last-child').remove() but this deletes everything between the body tag. I have also tried with

body = document.getElementsByTagName('body')[0];
   body.removeChild(body.lastChild);

this also doesnot work for me.

How can i delete this div?

Here i want to remove a last div of body as highlighted in image. I have tried with jqyery $('body :last-child').remove() but this deletes everything between the body tag. I have also tried with

body = document.getElementsByTagName('body')[0];
   body.removeChild(body.lastChild);

this also doesnot work for me.

How can i delete this div?

Share Improve this question asked Aug 3, 2017 at 19:36 Suraj KhanalSuraj Khanal 5409 silver badges28 bronze badges 4
  • It would be better if you can post the html over here instead of using an image – Anurag Singh Bisht Commented Aug 3, 2017 at 19:38
  • if you are using jquery, see this api.jquery./remove – tech2017 Commented Aug 3, 2017 at 19:38
  • "remove a last div of body": $('body').children('div').last().remove(); – Gavin Commented Aug 3, 2017 at 19:39
  • The problem with lastChild is that it takes white space text nodes into account. If you want the vanilla version, you can go with sth. like document.body.removeChild(document.body.children[document.body.children.length-1]); ... children only contains element children, so that works in this situation. But if you're using jQuery already, some of the existing answers are probably more suitable. – C3roe Commented Aug 3, 2017 at 19:50
Add a ment  | 

5 Answers 5

Reset to default 2

You can use $('body').children('div').last() to select last child div of body tag.

You can implement like following.

$('body').children('div').last().remove();
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div>1</div>
  <div>2</div>
  <div>3</div>
</body>

You can use .last() in jquery to select the last div, and then use empty() to remove from the div.

$('body div').last().empty()
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div>1</div>
  <div>2</div>
  <div>3</div>
</body>

Your selector needs to specify that you are looking at children elements of the body.

$('body>:last-child').remove()

What about

$('body').find('div:last-child').remove();

example

You want to select the last child of a body tag, not any body tag that is a last child. Try this:

$('body > :last-child').remove()

本文标签: javascriptHow to remove last child of body in DOMStack Overflow