简体   繁体   中英

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

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;
    }
}

This Will Work.

document.querySelector(".producer option[value='1']").text;

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 (eg if #abc is the select element etc).

The statement doesn't make sense. It gets the text from an option, and then just throws it away. I assume that you want to do something with the text, like assigning it to a variable.

// A variable for the result
var text = null;

// Get the options from the select element
var options = document.getElementById('abc').options;

// Find the option with the value "1"
for (var i = 0; i < options.length; i++) {
  if (options[i].value == '1') {
    // Get the text from the option
    text = options[i].text;
    // Exit from the loop
    break;
  }
}

Note: The original code would get the text from all options with the specified value, but this code only gets the text from the first option found. Having more than one option with the same value is pretty useless, so that feature of the original code is most likely unintended.

In modern browsers it can be:

var option = document.querySelector('#abc option[value="1"]').textContent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM