Reputation: 185
First, I am pretty new to Javascript. I am trying to grab the value of an object and I can see all the information I need in the console, I just don't know how to access it. For instance, I'm looking at an HTML Collection, made from a dropdown. It has:
>0: option
>2: option
value: "6"
text: "apple"
spellcheck: true
textContent: "apple"
>3: option
value: "2"
text: "test"
spellcheck: true
textContent: "test"
>4: option
...
Inside each of these are a whole host of parameters and values. My question is, how do I search, select the parameters and use the values, in JavaScript? Keep in mind, the order and number of "option" will change. Value, in this case, is something of - value - It uniquely identifies the text "test" and "apple".
I can list all these out, easily enough, by selecting them and outputting them in the in console...
var a = document.getElementById("whatever");
a
but how do I access all those sub-properties? Also, I don't know what the proper terminology is for these parameters and values, in order to effectively search Google for an answer, if someone could help me with that, as well.
Upvotes: 1
Views: 3368
Reputation: 7295
You can access those properties simply with a period, a.value
.
If you want to loop over a HTML collection, the simplest way is using a for loop:
var options = document.getElementsByTagName('option');
for (var i = 0; i < options.length; i++) {
var a = options[i];
// Get values
var value = a.value;
var text = a.textContent;
if (text == 'Audi') {
console.log('The value of "Audi" is ' + value);
}
}
<form>
<select>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
</form>
Upvotes: 1