Search code examples
javascriptgetelementsbytagname

getElementsByTagName returning undefined


I have a function with one parameter which is an ID string:

function experimentOne(masterContainer) {

Which I call with:

experimentOne('#experimentOne');

I'm trying to get each div inside that given DIV and place it into an array, which works if I use:

var menuButtons = $('#myDivIDHere').getElementsByTagName('div');

However, if I use:

var menuButtons = masterContainer.getElementsByTagName('div');

I get this error in the console.

TypeError: 'undefined' is not a function (evaluating 'parentContainer.getElementsByTagName('div', masterContainer)')

If I output $(masterContainer); to the console it returns the correct element, and this code is working perfectly:

var experimentOneMenuButton = $(masterContainer).children().last();

So I'm stumped, any ideas?

Thanks.


Solution

  • You need to use jQuery element selector

    var menuButtons = $('#myDivIDHere').find('div');
    

    or

    var menuButtons = $(masterContainer).find('div');
    

    in your experimentOne() method

    getElementsByTagName is a dom method, but $('#myDivIDHere') is a jQuery object where you don't have getElementsByTagName.

    If you want to use getElementsByTagName, you need to use $(masterContainer)[0].getElementsByTagName where $(masterContainer)[0] gives you the dom reference.