Languages
[Edit]
EN

jQuery - how to get element by id?

6 points
Created by:
JustMike
3515

In this post we cover how to get element by id with jQuery with interactive code examples.

Simples way to do it:

var element = $("#exampleId");

And 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 button

Interactive code 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 div

Interactive code 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>

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.