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>
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');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With