Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting DOM element value using pure JavaScript

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)" />
like image 500
Adam Halasz Avatar asked Nov 13 '10 16:11

Adam Halasz


People also ask

How do I get the value of a DOM element?

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.

How can we get elements from the DOM in JavaScript?

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.


1 Answers

Update: The question was edited. Both of the solutions are now equivalent.

Original answer

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.

like image 131
yorick Avatar answered Sep 21 '22 13:09

yorick