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?

1 thought on “Error: Cannot read property 'insertAdjacentHTML' of null in console”

  1. You have multiple possibilities:

    1. Paragraph with class "calender":
    document.querySelector('p.calender:last-of-type')
    
    1. Element with the classes "p" and "calender":
    document.querySelector('.p.calender:last-of-type')
    
    1. Select all elements either paragraph elements or calender class:
    document.querySelectorAll('.calendar, p:last-of-type')
    
    1. Paragraph inside an element with class "calender" will use your error-throwing code, so obviously that is not what you want.
    Reply

Leave a Comment