Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the ID of an element using jQuery?

<div id="test"></div> <script>   $(document).ready(function() {     alert($('#test').id);   });   </script> 

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

like image 542
fearofawhackplanet Avatar asked Jul 13 '10 17:07

fearofawhackplanet


People also ask

How can I get id in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.

How will you retrieve an element with the id first?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

Can we add id using jQuery?

We can add an id to an HTML element using jQuery very easily by combining the attr() method with a click event. Let's say we have the following HTML code and we want to give the user the ability to add an id to the paragraph. The new id will underline the paragraph content.


1 Answers

The jQuery way:

$('#test').attr('id') 

In your example:

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

Or through the DOM:

$('#test').get(0).id; 

or even :

$('#test')[0].id; 

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

$('#test').prop('id') 

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.

like image 141
instanceof me Avatar answered Oct 12 '22 06:10

instanceof me