EN
jQuery - get element by id
6
points
In this article, we would like to show you how to get an element by id with jQuery.
Quick solution:
var element = $("#exampleId");
And now we can make numerous operations on this selected element for example:
// change text of div
$("#div-id").text("Changed text.");
// change text of button
$("#button-id").text("Changed text.");
// change value of input
$("input-id").val("Hello world");
1. Change text of the button
Runnable example:
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
</head>
<body>
<button id="example-id">Change text button</button>
<script>
$(document).ready(function() {
var element = $('#example-id');
element.click(function() {
element.text('Text button has been changed');
});
});
</script>
</body>
</html>
2. Change text of the div
Runnable example:
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
</head>
<body>
<div id="example-id">Original text.</div>
<button>Change Text Button</button>
<script>
$(document).ready(function() {
var element = $("#example-id");
$("button").click(function() {
element.text("Changed text.");
});
});
</script>
</body>
</html>