So I have the following piece of HTML:
var hasOption1=$("option:contains('Option1')", "#sel").length==1; //true or false
var length = $('#sel option').filter(function() {
return $(this).text() === "Option1";
}).length;
if(length == 0)
console.log('This option text doesn't exist.');
else
console.log('This option text exists ' + length + ' times.');
If length is 0, it doesn't exist. I typically don't like using contains, because it's not an exact match.
Try the following:
var opt = 'Option1';
if ($('#sel option:contains('+ opt +')').length) {
alert('This option exists')
}
Demo
edit: The above snippet uses the jQuery contains
selector which filters elements that their textContent contains the specified value. For an exact match you can use the code snippet suggested in christian-mann's answer.
How to do this with Javascript (not jquery) – Jerry
var optionExists = [].some.call(document.getElementById('sel').options, function(option) {
return option.textContent === 'value';
});
The jQuery filter function accepts a function as its argument:
$('#sel option').filter(function() {
return $(this).text() === "Option1";
});