Search code examples
javascriptcssarraysdocument-body

Get All Elements in HTML body


I am trying to write a Javascript function to get all the elements in a HTML body. I tried something like:

function getAllElements(){
        let el = document.body.childNodes;
        for(var i=0; i<el.length; i++)
        {
            if(el[i].getAttribute("id") != "monkeyparentdiv" || el[i].getAttribute("id") != "monkeydiv"
            || el[i].getAttribute("id") != "monkeyspan1" || el[i].getAttribute("id") != "monkeyspan2")
            {
                el[i].classList.add("opacityformonkey");
            }
        }
}

And In the CSS I have

.opacity-for-monkey{
    animation-name: burnImage;
    animation-duration: 1s;
    animation-fill-mode: forwards;
}

@keyframes burnImage {
    from {
        opacity: 1
    }
    to {
        opacity: 0.3
    }
}

Long story short I want to set the opacity to 0.3 for all the elements except the ones mentioned in the if condition.
But it's giving me an error:

el[i].getAttribute is not a function.

What am I doing wrong?


Solution

  • document.body.childNodes returns all types of nodes including text nodes that don't have attributes. You should use document.body.children instead.

    Also, your JavaScript code adds the class opacityformonkey (no hyphens), but in CSS you have opacity-for-monkey (with hyphens).