Is there any difference between these solutions?
Solution 1:
function doSomething(id, value) { console.log(value); //... }
<input id="theId" value="test" onclick="doSomething(this.id, this.value)" />
...and Solution 2:
function doSomething(id) { var value = document.getElementById(id).value; console.log(value); //... }
<input id="theId" value="test" onclick="doSomething(this.id)" />
HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method.
The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object.
Update: The question was edited. Both of the solutions are now equivalent.
Yes, most notably! I don't think the second one will work (and if it does, not very portably). The first one should be OK.
// HTML: <input id="theId" value="test" onclick="doSomething(this)" /> // JavaScript: function(elem){ var value = elem.value; var id = elem.id; ... }
This should also work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With