Error: Cannot read property 'insertAdjacentHTML' of null in console

I have some code, but the problem is it is giving me an error: ‘ Cannot read property ‘insert-adjacent HTML’ of null’. It comes when I put this:

let lastone = document.querySelector('.calender p:last-of-type');
lastone.insertAdjacentHTML("afterend", getDayMarkUp());


function getDayMarkUp() {
   <p class="day"></p>
}

But I have no error when I put this:

let lastone = document.querySelector('p:last-of-type');
lastone.insertAdjacentHTML("afterend", getDayMarkUp());


function getDayMarkUp() {
   <p class="day"></p>
}

HTML:

<p></p> <!-- I need this paragraph! -->
<section class="calendar">
    <p>sun</p>
    <p>Mon</p>
    <p>Tue</p>
    <p>Wed</p>
    <p>Thur</p>
    <p>Fri</p>
    <p>Sat</p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
</section>

Can you tell me why the error is coming, and if possible how you solve it?

8 thoughts on “Error: Cannot read property 'insertAdjacentHTML' of null in console”

Leave a Comment