Jquery – How to get the ID of an element using jQuery


<div id="test"></div>
  $(document).ready(function() {

Why doesn't the above work, and how should I do this?

Best Solution

The jQuery way:


In your example:

$(document).ready(function() {
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>

Or through the DOM:


or even :


and reason behind usage of $('#test').get(0) in JQuery or even $('#test')[0] is that $('#test') is a JQuery selector and returns an array() of results not a single element by its default functionality

an alternative for DOM selector in jquery is


which is different from .attr() and $('#test').prop('foo') grabs the specified DOM foo property, while $('#test').attr('foo') grabs the specified HTML foo attribute and you can find more details about differences here.