Home »
jQuery »
jQuery Examples
document.getElementById() Vs. jQuery $()
Here, we are going to learn about the document.getElementById() and jQuery selector $(), which one is more efficient between document.getElementById() and jQuery $()?
Submitted by Pratishtha Saxena, on September 17, 2022
Prerequisite: Adding jQuery to Your Web Pages
What is document.getElementById()?
This is a common method to select different elements in JavaScript. The elements are selected based on their id. This means that when we need to select a particular element from the DOM page, we need to pass its already defined 'id' here. The ids are the unique string that is declared for an element to make it uniquely different from others.
Syntax:
const element = document.getElementById('id');
This method returns the element tag name, content, value, etc., and all other mentioned properties and attributes of that element.
jQuery document.getElementById() Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>This is a Heading Tag.</h2>
<p id="myPara">This is a tag with myPara as its ID.</p>
</body>
<script type="text/javascript">
const element = document.getElementById('myPara');
console.log(element);
</script>
</html>
Output:
What is jQuery Selector $()?
Now, $() is a jQuery's similar method. In jQuery, it helps to select the targeted elements using id, class, tag_name, etc as its selectors. Since nothing, in particular, is mentioned about how to select the element, we can use anything as a selector for the selection of the element. When using id as a selector, always use # in front of it. This denotes that the following string is the id of the element. Similarly, when using class as a selector, put a (.) dot ahead of the string. And if the element is selected using its tag name, then nothing special has to be denoted for this.
Syntax:
var contents = $('#id');
var contents = $('.class');
var contents = $('tag-name');
Similar to that in JavaScript, here also this method returns all the properties, attributes, content, and value of the selected element. This helps to access the selected jQuery object.
jQuery Selector $() Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<h2>This is a Heading Tag.</h2>
<p id="myPara">This is a tag with myPara as its ID.</p>
</body>
<script type="text/javascript">
$(document).ready(function(){
var contents = $('#myPara');
$(console.log((contents)));
});
</script>
</html>
Output: