Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of elements by class - TypeError: $.id is not a function

I'm trying to create an array from the elements of a div that all share a class.

The div's ID is settingsMenu and all of the elements I need to store in the array share a menuOption class. The JQuery attempt is as follows:

var options = $.id('settingsMenu').getElementsByClassName('menuOption');

When I execute the function with this statement inside, the error I get is:

"Uncaught TypeError: $.id is not a function"

The $.id seems to be problematic, am I using it wrong?

Dummy HTML:

<div id="settingsMenu">
    <input type="text" class="menuOption" />
    <input type="checkbox" class="menuOption" />
</div>
like image 546
Lolechi Avatar asked May 25 '26 01:05

Lolechi


2 Answers

If you want to use jQuery, then you don't need to use the pure Javascript functions like getElementsByClassName() as jQuery provides a very easy to use syntax for accessing DOM elements.

You could refactor your code as follows :

// This will retrieve all elements with the class "menuOption" below an element 
// with ID "settingsMenu"
var options = $('#settingsMenu .menuOption');
like image 95
Rion Williams Avatar answered May 26 '26 15:05

Rion Williams


Not totally sure I'd take this approach, nor have I seen this method for selecting an element by ID. Why not just nest the selector with the following?

var options = $('#settingsMenu .menuOption');

JSFiddle Link - demo


Be sure to check out the jQuery ID Selector (“#id”) docs as well as selectors in general

like image 30
scniro Avatar answered May 26 '26 14:05

scniro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!