Please help with this strange Id use

Hello I was analyzing this little code that I found on the internet and I just can’t figure out why on the js file it says: var s1 = document.getElementById(s1); and var s2 = document.getElementById(s2); when on the html file I don’t have any elements with the ids of s1 and s2.
On the .js part this s1 and s2 variables are used multiple times.
THANKS IN ADVANCE
CODEPEN
HTML

<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate(this.id,'slct2')">
  <option value=""></option>
  <option value="Chevy">Chevy</option>
  <option value="Dodge">Dodge</option>
  <option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2"></select>
<hr />

JS

function populate(s1,s2){
	var s1 = document.getElementById(s1);
	var s2 = document.getElementById(s2);
	s2.innerHTML = "";
	if(s1.value == "Chevy"){
		var optionArray = ["camaro|Camaro","corvette|Corvette","impala|Impala"];
	} 
  else if(s1.value == "Dodge"){
		var optionArray = ["avenger|Avenger","challenger|Challenger","charger|Charger"];
	} else if(s1.value == "Ford"){
		var optionArray = ["mustang|Mustang","shelby|Shelby"];
	}
	for(var option in optionArray){
		var pair = optionArray[option].split("|");
		var newOption = document.createElement("option");
		newOption.value = pair[0];
		newOption.innerHTML = pair[1];
		s2.options.add(newOption);
	}
}

Hello @codeca423
s1 and s2 are just parameters to the populate onchange event handler. They are replaced when you pass arguments when invoking the function.

Essentially when it is invoked inline onchange="populate(this.id,'slct2')" , the arguments passed are this.id, which is the id of select and 'slct2'. s1 and s2 take the values slct1 and slct2 respectively. It is like writing a function which adds two values like:

function add(value1, value2){
    return value1  + value2;
}

When you invoke add like add( 2, 3), inside the function, value1 and value2 take the values 2 and 3 respectively as a result you get 5.

thanks for the help this is a bit more complicated stuff but with practice I hope to understand it better, thanks

Yes. Definitely you need to understand functions to make sense of what is happening above.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.