document.getElementsByClassName('name') has a length of 0

keunicek

I'm trying to retrieve all the elements by class name by using the method getElementsByClassName (no jQuery). Console.log shows the array of the elements, but when I try to get the length of the array, it returns 0.

Saw a previous post with a similar problem that provided a solution of making sure that the element exists. I took this into consideration and fire the function after DOMcreation.

What is going on here?

document.addEventListener("DOMContentLoaded", function(){
    // Load current todo items from db
    loadTodoItems();

    var submitBtn = document.getElementById('submit-btn');
    submitBtn.addEventListener('click', addItem);

    var removeButton = document.getElementsByClassName("remove-btn");
    console.log(removeButton);
    console.log(removeButton.length);


}, false)

Another issue to note, is that I am noticing that in chrome Dev Tools when I look at the head tag, I'm seeing that some sort of angular code is being loaded in a script tag in the head, while the content that should be in my head tag are being loaded in the body. I am not using angular for my app.

Edit. Here is my HTML. It is in Jade:

Layout.jade:

doctype html
html(lang='en')
head
   meta(charset="utf-8")
   title To Do List
   link(rel="stylesheet" href="main.css")

body
    block content
    script(src="main.js")

index.jade: extends layout

block content
    div.container
        h1 Get-Er-Done! 

        form#todo-form(role="form" method="POST" action="/todo")
            div.form-group
                label(for="addToDo") Add To-Do item:
                input#todoItemText.form-control(type="text")
                button(type="submit")#submit-btn.btn.btn-default Add

        ul#todo-list

Edit. The remove button is for the new todo item. This is called every time the user clicks add to post the new item.

function renderItems(items){
// Before rendering todo-items, clear the existing items in the list
var list = document.getElementById('todo-list');
while(list.hasChildNodes()){
    list.removeChild(list.lastChild);
}

// Loop through items
for (var i = 0; i < items.length; i++) {
    var el = document.createElement("li");

    var removeBtn = document.createElement('button');
    var btnText = document.createTextNode('Done');
    removeBtn.appendChild(btnText);
    removeBtn.className = 'remove-btn';

    var newItemText = document.createTextNode(items[i].item);
    el.appendChild(newItemText); // Add new content to new div
    el.appendChild(removeBtn);


    // To-Do list to append to 
    list.appendChild(el);
}
}
Oriol

Length is 0 because when you run it there's no element with class remove-btn. You can see the items in the console because getElementsByClassName returns a live HTMLCollection, which is updated when new elements are added.

The problem is that you create the elements with that class in renderItems, which runs after you run getElementsByClassName.

You can fix it using

function renderItems(items){
    var list = document.getElementById('todo-list');
    while(list.hasChildNodes()){/* ... */}
    for (var i = 0; i < items.length; i++) {/* ... */}


    // Load current todo items from db
    loadTodoItems();

    var submitBtn = document.getElementById('submit-btn');
    submitBtn.addEventListener('click', addItem);

    var removeButton = document.getElementsByClassName("remove-btn");
    console.log(removeButton);
    console.log(removeButton.length);

}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

HTML getElementsByClassName returns HTMLCollection with length of 0

document.getElementsByClassName("...")[0] returning undefined

Array has elements but length is 0

Issue with document.getElementsByClassName

loop document.getElementsByClassName

get directly first Object in Javascript document.getElementsByClassName(element)[0] without using [0]

array length is 0 even though it has values

Array shows 0 as length when it has elements in it

Array length is 0 even though it has items

c# array has always the length of 0

why doesn't this javascript code work document.getElementsByClassName("para")[0].innerHTML.style.visibility = "hidden";

Is getElementById or getElementsByClassName[0] faster?

Using document.getElementsByClassName in Testcafe

document.getElementsByClassName() not working properly?

javascript document.getElementsbyClassName is not a function

why document.getElementsByName().length always return 0?

GetElementsByClassName('..')[0].value = '' does not work

Does HTML tag name has a max size ( length )

Angular 2 array after subscribe has elements but length is 0

dictionary update sequence element #0 has length 15; 2 is required

Why the length of the ViewContainerRef is 0 even if it has other components inside

My array appears to have entries but it has a length of 0

dictionary update sequence element #0 has length 3; 2 is required

IndexOutOfRangeException in C# – Why has length of array become 0?

c++ empty char array has length > 0

Array has records but showing array length 0 in console

dictionary update sequence element #0 has length 4; 2 is required

Length of getElementsByClassName() array changes when removing class

Get the value of input text with document.getElementsByClassName