javascriptcreateelementsetattribute

setAttribute for created element


I have already 3 paragraphs and need to create the 4th one using JavaScript It's created successfully.

const new_h2 = document.createElement('h2')

and assigns an ID to the h2

new_h2.setAttribute('id', 'heading4');

now I get that h2 with its ID

const heading4 = document.getElementById('heading4')

The problem appears when I try to use it in an If statement

    window.addEventListener('scroll', function(){
        console.log(window.scrollY);
        if(window.scrollY >= 400 && window.scrollY < 800){
            heading1.style.color = '#cc1'
            // console.log('section1 is styled');
        }else if(window.scrollY >= 800 && window.scrollY < 1200){
            heading2.style.color = '#cc1'
            // console.log('section2 is styled');
        }else if(window.scrollY >= 1200 && window.scrollY < 1600){
            heading3.style.color = '#cc1'
            // console.log('section3 is styled');
        }else if(window.scrollY >= 1600){
            heading4.style.color = '#cc1'
            // console.log('section4 is styled');
        }else{
            heading1.style.color = '#fff'
            heading2.style.color = '#fff'
            heading3.style.color = '#fff'
            heading4.style.color = '#fff'
        }
})

The log shows the following error: Cannot read properties of null (reading 'style') and I guess that comes from heading4.style.color but I don't know how to deal with it.


Solution

  • It sounds like you never add new_h2 to the page. Since it's not in the page's DOM, getElementById("heading4") returns null — there's no element in the DOM with that id:

    const new_h2 = document.createElement("h2");
    
    new_h2.setAttribute("id", "heading4");
    
    console.log(document.getElementById("heading4")); // null
    
    // Add the element to the page's DOM
    document.body.appendChild(new_h2);
    
    console.log(document.getElementById("heading4")); // finds it

    You need to add the element to the DOM in order to find it in the DOM with methods like getElementById or querySelector.

    But note that you already have a reference to the element (new_h2). There's no need to look it up, and probably no need for it to have an id. Just use new_h2. (You probably still have to add it to the page though.)


    Side note: You don't need to use setAttribute to set an element's id, you can use the reflected property for it:

    new_h2.id = "heading4";
    

    Most (but not all) useful attributes have reflected properties. You can see which ones do on MDN or in the spec.