1

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.

3
  • In your getElementById example, what is a? Do you want the property a.value directly? Or is there a <select id="whatever">? Commented May 8, 2019 at 2:46
  • All the properties and methods you can access: w3schools.com/jsref/dom_obj_all.asp Commented May 8, 2019 at 2:51
  • How about a.value or a.text or a.textContent? Commented May 8, 2019 at 3:05

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.