Unable to find an element by id, but I am able to find it by class

1.3k Views Asked by At

As the title suggests I am unable to find an element by its ID, but I am able to find it by class name.

I am a noob at Javascript.

HTML:

<div class="pleaseWork" id="map" style="width:100%;height:300px"></div>

JS Function:

function initMap() {
var mapDiv = document.getElementsByClassName("pleaseWork")
console.log('Find by class: ')
console.log(mapDiv)


var mapDivId = document.getElementById('map')
console.log('Find by id: ')
console.log(mapDivId)
}

The output in console (Chrome debugger) is this:

enter image description here

Also when accessing the first element of the HTMLCollection, it returns 'undefined'.

So console.log(document.getElementsByClassName("pleaseWork")[0])

prints 'undefined'

1

There are 1 best solutions below

0
On

Everything works correctly for me in the snippet, make sure you call the function after the DOM is loaded.

function initMap() {
    var mapDiv = document.getElementsByClassName("pleaseWork");
    console.log('Find by class: ');
    console.log(mapDiv);


    var mapDivId = document.getElementById('map');
    console.log('Find by id: ');
    console.log(mapDivId);
};

//this will wait for the DOM to load before calling the function
window.addEventListener("DOMContentLoaded", function(){
    initMap();
});
<div class="pleaseWork" id="map" style="width:100%;height:300px"></div>