Search code examples
javascriptloopschild-nodes

js loop through clicked elements childnodes


js loop through clicked elements childnodes and i have error : Uncaught TypeError: Cannot read property 'contains' of undefined

I need to compare if one of them have class task-value and i cant understand why i have the error!!! Need Help sorry for bad English Link to js fiddle whith code

Link to code on js fiddle

function docClick(e) {
    var target = e.target;
    console.log(this.childNodes.length)

    for(var i = 0; i < this.childNodes.length; i++){
        console.log(this.childNodes[i])

        if(this.childNodes[i].classList.contains("task-value")){
            console.log("if")
        }else{
            console.log("else")
        }
    }

Link UpDate whit full css/Html and Javascript


Solution

  • This become possible because this.childNodes contains not only HTML elements but text nodes too. Text nodes can't have classes so them never have property classList You need to use property children to get exactly html elements

    function docClick(e) {
        var target = e.target;
        console.log(this.children.length)
    
        for(var i = 0; i < this.children.length; i++){
            console.log(this.children[i])
    
            if(this.children[i].classList.contains("task-value")){
                console.log("if")
            }else{
                console.log("else")
            }
        }