Search code examples
javascriptthisselectedindex

Advantage to using the this keyword with selectedIndex?


Is there any advantage to this:

document.getElementById('mySelectBox').options[this.selectedIndex].value

over this:

document.getElementById('mySelectBox').options[selectedIndex].value

Just curious. Thanks!


Solution

  • Yes, if you don't use this, you will be accessing a variable instead of the property in the object.

    Javascript isn't object oriented, so you are never in the scope of an object, where you could access properties without specifying which object they belong to.

    Anyway, if this refers to the element, just use:

    this.options[this.selectedIndex].value