JQuery Syntax

JQuery is used for the selection of elements, and then performing actions on them. Let's have a look towards the jQuery syntax:


Syntax


  • A statement in jQuery generally starts with the ($) sign, this sign also defines the query
  • The $(document).ready(handler) displays the document ready event and it is efficient to carry out the jQuery code once the file is ready.
  • The jQuery ready() procedure is generally used with an unidentified function.

$(selector)

It sorts out the HTML components from the DOM tree so that it can be operated.


action()

It executes a procedure on the chosen components. Let's have a look at an example:



$(document).ready(function(){
  //JQuery methods go here
  alert('Page loaded successfully!');
});

Live Demo!

Let's put the JQuery code in our HTML document.


Example:


<!DOCTYPE html>
<html lang="en">
<head>
<title>Learning jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>

<p>Hello World </p>
<script>
  $(document).ready(function(){
    $('p').text('This is new text');
  });
</script>
</body>
</html>

Live Demo!

JavaScript events are extremely easy to implement in JQuery. Let's see how we can handle an onclick event in JQuery


Example:


<!DOCTYPE html>
<html lang="en">
<head>
<title>Learning jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>

<p>Hello World </p>
<button>Replace Text</button>

<script>
$(document).ready(function(){
  $("button").click(function(){
    $('p').text('This is new text');
  });
});
</script>

</body>
</html>

Live Demo!


In the above example, we have a text 'Hello World' & a button. As soon as the user clicks on the button, the texts gets replaced with 'This is new text' using JQuery.