Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript equivalent of jquery code

Can someone help what's the javascript equivalent of below jquery line.

$("#abc option[value='1']").text();

abc is the id of selectbox

like image 456
Sunil kumar Avatar asked Jan 29 '26 05:01

Sunil kumar


2 Answers

var options = document.getElementById("abc").options;
for (var i = 0, j = options.length; i < j; i++) {
    if (options[i].value == "1") {
        alert(options[i].text);
    }
}

The value and text attributes are available on the HTMLOptionElement per DOM Level 2.

(demo)


UPDATE
Updated demo with combined text, cf. comments:

var options = document.getElementById("abc").options,
    text = "";

for (var i = 0, j = options.length; i < j; i++) {
    if (options[i].value == "1") {
        text += options[i].text;
    }
}
like image 157
jensgram Avatar answered Jan 31 '26 19:01

jensgram


This would be 100% equivalent to the selector:

var options = document.getElementById('abc').getElementsByTagName('option'),
    text = "";

for(var i = 0, l = options.length; i < l; i++) {
    var option = options[i];
    if(option.value === '1') {
        text += option.text;
    }
}

Or if querySelectorAll is available:

var options = document.querySelectorAll('#abc option[value="1"]'),
    text = "";
for(var i = 0, l = options.length; i < l; i++) {
    text += options[i].text;
}

That said, you can make improvements depending on the HTML structure (e.g. if #abc is the select element etc).

like image 35
Felix Kling Avatar answered Jan 31 '26 20:01

Felix Kling



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!