How can I get the ID of an HTML element in a JavaScript function without passing any parameters?
I have a HTML element:
<input type="text" id="exampleInput" value="0" onkeypress="exampleFunction()">
From JavaScript, I would like to change the value of the HTML element.
function exampleFunction() {
}
Is it possible to achieve this without passing the ID as a parameter?
You can pass this
to your function like this:
function exampleFunction(e) { console.log(e); // element console.log(e.id); // id e.value = 'new value'; // change value }
<input type="text" id="exampleInput" value="0" onkeypress="exampleFunction(this)">
Or, better yet, use addEventListener
instead:
document.getElementById('exampleInput').addEventListener('keypress', function (e) { console.log(e.target); // element console.log(e.target.id); // id e.target.value = 'new value'; // change value });
<input type="text" id="exampleInput" value="0">
You can pass the element into the function as this
.
function exampleFunction(element) { console.log(element.value); }
<input type="text" id="exampleInput" value="0" onkeypress="exampleFunction(this)">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.