JQuery Check if Element Exists using this simple piece of code. To check this in the current page, we need to check the length of the element returned by the JQuery selector, if it returns you something then the element must exists otherwise no.
if( $('#EleSelector').length ) { // use this if you are using id, replace EleSelector with the id
// it exists
}
if( $(‘.EleSelector’).length ) { // use this if you are using class, replace EleSelector with the id
// it exists
}
In case of plain javascript try this:
//you can use it for more advanced selectors
if(document.querySelectorAll("#EleSelector").length){}
if(document.querySelector("#EleSelector")){}
//you can use it if your selector has only an Id attribute
if(document.getElementById("EleSelector")){}
Update (2025): This guide has been updated with modern ES6+ methods and troubleshooting FAQs to ensure it works with the latest web standards and frameworks.
Iterating through dropdown (select) options is a fundamental task in web development. Whether you are validating a form, dynamically filtering data, or syncing UI states, knowing how to efficiently loop through a <select> element’s options is essential for a smooth user experience.
In this guide, we will cover the modern ES6+ way, the traditional approach, and the jQuery method.
1. Modern JavaScript (ES6+) — Recommended
The most efficient and readable way to handle this today is by converting the HTMLOptionsCollection into an array and using the forEach method. This is the standard in modern frameworks like React, Vue, or Vanilla JS projects.
JavaScript
// Get the dropdown by ID
const dropdown = document.getElementById("dropdownlist");
// Convert options to an Array and iterate
Array.from(dropdown.options).forEach((option) => {
console.log("Text:", option.text, "Value:", option.value);
// Add your custom logic or operations here
});
2. The Traditional JavaScript Loop
If you need to support legacy browsers (like very old versions of IE) or prefer the standard for loop, use the code below. It is highly performant as it avoids creating an array copy.
JavaScript
var x = document.getElementById("dropdownlist");
for (var i = 0; i < x.options.length; i++) {
console.log("Value: " + x.options[i].value);
// Perform operations based on each option
}
3. The jQuery Approach
If your project is already utilizing the jQuery library, the .each() method provides a very concise and readable syntax for targeting child options.
How do I select a specific value while iterating? You can add a simple conditional check inside your loop. For example: if (option.value === "target") { option.selected = true; }
How do I get the total count of options in a dropdown? You can simply access the length property: document.getElementById("dropdownlist").options.length;
Can I iterate through a dropdown without using an ID? Yes, you can use document.querySelector('select') or document.getElementsByClassName('your-class') to target the element without an ID.