0

I have this HTML

<select id="tempSelect" >
    <option value="F">Fahrenheit</option>
    <option value="C">Celsius</option>
</select>

I want to get the selected Option Value using Tag Name Not ID . I tried this using document.getElementById() it works fine but I want to do it by tag name. I searched a lot but could not found the solution so far.

Here is my Java script Code

var parent = document.getElementsByTagName('select');
var tempUnit = parent.options[parent.selectedIndex].value;

1 Answer 1

2

document.getElementsByTagName() returns an HTMLCollection(which is a kind of an array), so it does have the options properties. You can access the items in the list using indexing.

var parent = document.getElementsByTagName('select')[0];
var tempUnit = parent.options[parent.selectedIndex].value;

document.querySelector('#result').innerHTML = tempUnit
<select id="tempSelect" >
    <option value="F">Fahrenheit</option>
    <option value="C" selected>Celsius</option>
</select>
<div id="result"></div>

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.