There are a number of ways to do what you are asking. Keep in mind that the return value of querySelectorAll
is an array-like NodeList which can be accessed using standard array syntax, implements some array methods (forEach for example) or can be coerced to an array.
If you want to keep working with the result of querying all img
elements in your div you can simply access the last element in the returned NodeList and remove it.
const images = document.querySelectorAll('.content img');
images[images.length-1].remove();
// or spread the NodeList to an array and pop
[...document.querySelectorAll('.content img')].pop().remove();
Alternatively, you can query the last img
element directly using either :last-child
or :last-of-type
document.querySelector('.content img:last-child').remove();
// or
document.querySelector('.content img:last-of-type').remove();
document
.getElementById('lastchild')
.addEventListener('click', () => document.querySelector('.content img:last-child').remove());
document
.getElementById('lasttype')
.addEventListener('click', () => document.querySelector('.content1 img:last-of-type').remove());
document
.getElementById('lastindex')
.addEventListener('click', () => {
imgs = document.querySelectorAll('.content2 img');
imgs[imgs.length - 1].remove()
});
document
.getElementById('pop')
.addEventListener('click', () => [...document.querySelectorAll('.content3 img')].pop().remove());
<div class="content">
<img src="https://source.unsplash.com/random/100x100/?sig=1"/>
<img src="https://source.unsplash.com/random/100x100/?sig=2"/>
<img src="https://source.unsplash.com/random/100x100/?sig=3"/>
<img src="https://source.unsplash.com/random/100x100/?sig=4"/>
</div>
<button type='button' id='lastchild'>Remove :last-child</button>
<hr>
<div class="content1">
<img src="https://source.unsplash.com/random/100x100/?sig=5"/>
<img src="https://source.unsplash.com/random/100x100/?sig=6"/>
<img src="https://source.unsplash.com/random/100x100/?sig=7"/>
<img src="https://source.unsplash.com/random/100x100/?sig=8"/>
</div>
<button type='button' id='lasttype'>Remove :last-of-type</button>
<hr>
<div class="content2">
<img src="https://source.unsplash.com/random/100x100/?sig=9"/>
<img src="https://source.unsplash.com/random/100x100/?sig=10"/>
<img src="https://source.unsplash.com/random/100x100/?sig=11"/>
<img src="https://source.unsplash.com/random/100x100/?sig=12"/>
</div>
<button type='button' id='lastindex'>Remove imgs[length-1]</button>
<hr>
<div class="content3">
<img src="https://source.unsplash.com/random/100x100/?sig=13"/>
<img src="https://source.unsplash.com/random/100x100/?sig=14"/>
<img src="https://source.unsplash.com/random/100x100/?sig=15"/>
<img src="https://source.unsplash.com/random/100x100/?sig=16"/>
</div>
<button type='button' id='pop'>Remove pop()</button>