Languages
[Edit]
EN

jQuery - get element by id

6 points
Created by:
Dexter
660

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>

Alternative titles

  1. jQuery - how to get element by id?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

jQuery

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join