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
CodePudding user response:
const divs = document.querySelectorAll('div')
divs[divs.length - 1].remove()
CodePudding user response:
A possible solution:
document.body.children[
document.body.children.length - 1
].remove()
CodePudding user response:
Or use document.getElementsByTagName.
let last = document.getElementsByTagName('div');
console.log(last[last.length-1]);
last[last.length-1].remove()
<body>
<div>don't delete</div>
<div>don't delete</div>
<div>don't delete</div>
<div>delete this div</div>
</body>
CodePudding user response:
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>
