<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
Why doesn't the above work, and how should I do this?
<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
Why doesn't the above work, and how should I do this?
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.
$('selector').attr('id')
will return the id of the first matched element. Reference.
If your matched set contains more than one element, you can use the conventional .each
iterator to return an array containing each of the ids:
var retval = []
$('selector').each(function(){
retval.push($(this).attr('id'))
})
return retval
Or, if you're willing to get a little grittier, you can avoid the wrapper and use the .map
shortcut.
return $('.selector').map(function(index,dom){return dom.id})
id
is a property of an html Element
. However, when you write $("#something")
, it returns a jQuery object that wraps the matching DOM element(s). To get the first matching DOM element back, call get(0)
$("#test").get(0)
On this native element, you can call id, or any other native DOM property or function.
$("#test").get(0).id
That's the reason why id
isn't working in your code.
Alternatively, use jQuery's attr
method as other answers suggest to get the id
attribute of the first matching element.
$("#test").attr("id")
Well, seems there has not been a solution and would like to propose my own solution that is an expansion of the JQuery prototype's. I put this in a Helper file that is loaded after the JQuery library, hence the check for window.jQuery
if (window.jQuery) {
$.prototype.id = function () {
if (this.length > 1) {
var val = [];
this.each(function (idx, el) {
val.push($(el).id());
});
return val;
} else {
return this.attr('id');
}
}
}
It may not be perfect but it is a start to maybe getting inclusion into the JQuery library.
Returns either a single string value or an Array of string values. The Array of string values, is for the event an multi-element selector was used.
Maybe useful for others that find this thread. The code below will only work if you already use jQuery. The function returns always an identifier. If the element doesn't have an identifier the function generates the identifier and append this to the element.
var generatedIdCounter = 0;
$.fn.id = function() {
var identifier = this.attr('id');
if(!identifier) {
generatedIdCounter++;
identifier = 'isGenerated_' + generatedIdCounter;
this.attr('id', identifier);
}
return identifier;
}
How to use:
$('.classname').id();
$('#elementId').id();
This is an old question, but as of 2015 this may actually work:
$('#test').id;
And you can also make assignments:
$('#test').id = "abc";
As long as you define the following JQuery plugin:
Object.defineProperty($.fn, 'id', {
get: function () { return this.attr("id"); },
set: function (newValue) { this.attr("id", newValue); }
});
Interestingly, if element
is a DOM element, then:
element.id === $(element).id; // Is true!
This will finally solve your problems:
lets say you have many buttons on a page and you want to change one of them with jQuery Ajax (or not ajax) depending on their ID.
lets also say that you have many different type of buttons (for forms, for approval and for like purposes), and you want the jQuery to treat only the "like" buttons.
here is a code that is working: the jQuery will treat only the buttons that are of class .cls-hlpb, it will take the id of the button that was clicked and will change it according to the data that comes from the ajax.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$(".clshlpbtn").on('click',function(e){
var id = $(e.target).attr('id');
alert("The id of the button that was clicked: "+id);
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
//parsing the data should come here:
//var obj = jQuery.parseJSON(data);
//$("#"+id).val(obj.name);
//etc.
if (id=="btnhlp-1")
$("#"+id).attr("style","color:red");
$("#"+id).val(data);
});
});
});
</script>
</head>
<body>
<input type="button" class="clshlpbtn" id="btnhlp-1" value="first btn"> </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-2" value="second btn"> </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-9" value="ninth btn"> </input>
</body>
</html>
code was taken from w3schools and changed.
<html>
<head>
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<?php
// include Database connection file
include("db_connection.php");
// Design initial table header
$data = '<table class="table table-bordered table-striped">
<tr>
<th>No.</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>Update</th>
<th>Delete</th>
</tr>';
$query = "SELECT * FROM users";
if (!$result = mysqli_query($con, $query)) {
exit(mysqli_error($con));
}
// if query results contains rows then featch those rows
if(mysqli_num_rows($result) > 0)
{
$number = 1;
while($row = mysqli_fetch_assoc($result))
{
$data .= '<tr>
<td>'.$number.'</td>
<td>'.$row['first_name'].'</td>
<td>'.$row['last_name'].'</td>
<td>'.$row['email'].'</td>
<td><button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
</td>
</tr>';
$number++;
}
}
else
{
// records now found
$data .= '<tr><td colspan="6">Records not found!</td></tr>';
}
$data .= '</table>';
echo $data;
?>
<script type="text/javascript">
function DeleteUser(id) {
var conf = confirm("Are you sure, do you really want to delete User?");
if (conf == true) {
$.ajax({
url:'deleteUser.php',
method:'POST',
data:{
id:id
},
success:function(data){
alert('delete successfully');
}
}
});
deleteUser.php
<?php
// check request
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
// include Database connection file
include("db_connection.php");
// get user id
$user_id = $_POST['id'];
// delete User
$query = "DELETE FROM users WHERE id = '$user_id'";
if (!$result = mysqli_query($con, $query)) {
exit(mysqli_error($con));
}
}
?>