Reputation: 3245
This code below works fine in chrome, Firefox and Edge. But when I try this same code in html I get the following error.
SCRIPT5009: 'ddlTest' is undefined
<select id="ddlTest">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<script>
function testFunc() {
var y = (ddlTest).value;
alert(y);
}
</script>
Is there a way I can get around this in IE , other than doing :
document.getElementById('ddlTest').value
Upvotes: 0
Views: 68
Reputation: 980
The feature to have a property on window
to access an element by ID was added in HTML5.
The HTML5 standard specifies that the
window
object must have a property key whose value is elem if...
- there is exactly one DOM element elem whose property
id
has the value key.- there is exactly one DOM element elem whose property
name
has the value key. elem’s tag must be one of: a, applet, area, embed, form, frame, frameset, iframe, img, object.
~ http://2ality.com/2012/08/ids-are-global.html
However, you should not use this in your actual code -- use document.getElementById('elem')
instead:
As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use
document.getElementById()
ordocument.querySelector()
.
~ https://html.spec.whatwg.org/multipage/nav-history-apis.html#named-access-on-the-window-object
Upvotes: 4
Reputation: 1102
No, the only way to do it is to get the element through the document:
function testFunc() {
var ddlTest = document.getElementById('ddlTest');
var y = ddlTest && ddlTest.value;
alert(y);
}
Upvotes: 0