Skip to content
Fix Code Error

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

March 13, 2021 by Code Error
Posted By: Anonymous
<div id="test"></div>
<script>
  $(document).ready(function() {
    alert($('#test').id);
  });  
</script>

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

Solution

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.

Answered By: Anonymous

Related Articles

  • How does PHP 'foreach' actually work?
  • For-each over an array in JavaScript
  • setTimeout function not working : javascript
  • sql query to find priority jobs
  • Use of Jquery on scroll event
  • Ukkonen's suffix tree algorithm in plain English
  • How to create an alert the fade after a duration in Vuetify?
  • jQuery.on() Delegation: Slightly complex selector…
  • Usage of __slots__?
  • What is the origin of foo and bar?
  • How can I access and process nested objects, arrays or JSON?
  • jQuery Mobile: document ready vs. page events
  • What are the undocumented features and limitations…
  • What's the best way to get the last element of an…
  • data.table vs dplyr: can one do something well the…
  • What is an application binary interface (ABI)?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • What is your most productive shortcut with Vim?
  • How to detect if multiple keys are pressed at once…
  • Error 'Map', but got one of type 'Null' flutter web…
  • Sort table rows In Bootstrap
  • Logging best practices
  • Best way to communicate between instances of the…
  • How can I manually compile a svelte component down…
  • SQL query return data from multiple tables
  • How to write down nested schemas for mongoose using…
  • Shell Script Syntax Error: Unexpected End of File
  • Expanded calendar in modal
  • Start redis-server with config file
  • "Thinking in AngularJS" if I have a jQuery background?
  • Backbone Collection.fetch gives me Uncaught…
  • Is this request generated by EF Core buggy or is it my code?
  • How to convert networkx node positions to…
  • What's the difference between eval, exec, and compile?
  • Pure JavaScript equivalent of jQuery's $.ready() -…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • What are the nuances of scope prototypal /…
  • How do you clear the SQL Server transaction log?
  • jQuery .each() index?
  • Not submit any value if checkbox is empty
  • The definitive guide to form-based website authentication
  • Difference between variable declaration syntaxes in…
  • Am I paranoid? "Brutally" big Polymer website after…
  • Is it possible to apply CSS to half of a character?
  • How does the @property decorator work in Python?
  • Smart way to truncate long strings
  • How to use setTimeout on vuex action?
  • How to use Servlets and Ajax?
  • How can I, in Vue, define a local data property that…
  • Get operating system info
  • What does AngularJS do better than jQuery?
  • Identifying and solving…
  • Why does C++ code for testing the Collatz conjecture…
  • d3.js - draw arrow line from border to border
  • @selector() in Swift?
  • What is an IndexOutOfRangeException /…
  • Polymer 1.0 'array-style' path accessors,…
  • What is a NullReferenceException, and how do I fix it?
  • Get the name of an object's type
  • What is the copy-and-swap idiom?
  • .prop() vs .attr()
  • How can I find the product GUID of an installed MSI setup?
  • D3.js: Update barplot based on variable input
  • Onclick, the button moves down, why can that due to?
  • In CSS Flexbox, why are there no "justify-items" and…
  • Bootstrap Alert Auto Close
  • Memcached vs. Redis?
  • How do you parse and process HTML/XML in PHP?
  • Callback functions in C++
  • What is the scope of variables in JavaScript?
  • Javascript text animation not triggering
  • How do I return the response from an asynchronous call?
  • I want to create a SQLite database like in the…
  • How do I pass data in $router.push in Vue.js?
  • Twitter bootstrap flex vertical center does not work…
  • image preview from thumbnail on click and with…
  • How do I use arrays in C++?
  • Fastest way to flatten / un-flatten nested JSON objects
  • What are the currently supported CSS selectors…
  • call a component from another component in vue.js
  • How do I initialize a TypeScript Object with a JSON-Object?
  • Load and execution sequence of a web page?
  • How do Mockito matchers work?
  • What does this symbol mean in JavaScript?
  • Jquery chosen remove attributes by name or id
  • does Backbone.Models this.get() copy an entire array…
  • Property or method "key" is not defined on the…
  • What is Ember RunLoop and how does it work?
  • How do I add a simple onClick event handler to a…
  • What does "Could not find or load main class" mean?
  • How can I get the image name currently being…
  • How should a model be structured in MVC?
  • How can I create a Promise in TypeScript from a union type
  • What does "Fatal error: Unexpectedly found nil while…
  • VUE Error when run test unit
  • performSelector may cause a leak because its…
  • anime.js not targetting elements
  • How to implement the factory method pattern in C++ correctly
  • CSS selector for first element with class
  • How do I merge two dictionaries in a single…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

I need an unordered list without any bullets

Next Post:

HTML text input allow only numeric input

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error