1

If I had div's without id's or anything, but with the information that it is the last thing before the tag, is there a way I can use javascript to delete it? Example:

<body>
<div>don't delete</div>
<div>don't delete</div>
<div>don't delete</div>
<div>delete this div</div>
</body>

Thanks (I'm sorry if my question sucks, please tell me how I can improve it)

I also would not like to use jQuery

Eric Pan
  • 34
  • 3
  • 1
    Duplicate: [Selecting a last child in javascript](https://stackoverflow.com/questions/13308906/selecting-a-last-child-in-javascript) –  Jan 13 '22 at 23:54
  • Eric, the duplicate doesn't have to be exact. A programmer needs to be capable of applying a (suitable) solution to a slightly different problem, or they might as well give up. The solution is `document.querySelector("body *:last-of-type").remove();` and can be inferred from the dupe. –  Jan 14 '22 at 08:29

1 Answers1

2

You can also use a plain CSS selector to get the last div immediately, instead of retrieving a collection.

document.querySelector('body > div:last-of-type').remove();
<body>
  <div>don't delete</div>
  <div>don't delete</div>
  <div>don't delete</div>
  <div>delete this div</div>
</body>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320