Reputation: 1516
I am trying to capture the ID of the element being clicked when a user clicks on an element which allows him to leave a page. The idea is to then record this using Ajax. The script below seems to be working fine as long as the element has an ID, but it does not seem to be able to climb the DOM to find an ancestor's ID if it has not. What am I doing wrong?
$(document).ready(function(){
$('a, button, input[type=submit]').on('click', function (event) {
if (event.target.id == '')
alert($(this).closest('[id!=""]').attr('id'));
else
alert(event.target.id);
});
});
Upvotes: 2
Views: 553
Reputation: 54659
The issues with your code is that you're only checking if the id attribute of the clicked element is empty but you're not checking if it's actually present. Also it seems that the [id!=""]
selector is not working correctly but I found that adding [id]
before to force the element to have an id makes it work, so the more concise solution would be this:
$(document).ready(function(){
$('a, button, input[type=submit]').on('click', function () {
var id = this.id ? this.id : $(this).closest('[id][id!=""]').attr('id');
alert(id);
});
});
Upvotes: 1
Reputation: 1961
Here a way to look recursively through the DOM for an ID attribut:
$(document).ready(function () {
$('a, button, input[type=submit]').on('click', function (event) {
getID($(this));
});
function getID(element) {
if (element.attr('id') && element.attr('id') !== "") {
alert(element.attr('id'));
} else if (element.parent()) {
getID(element.parent());
}
}
});
Upvotes: 1
Reputation: 1109
I believe this would recursively find the IDs
$(document).on('click', 'a, button, [type="submit"]', function() {
findID($(this));
});
function findID(element) {
if(element.attr('id') === undefined || element.attr('id') === null) {
var temp = element.parent().attr('id');
if(temp === undefined || temp === null){
findID(element.parent());
} else {
alert(temp);
}
} else {
alert(element.attr('id'));
}
}
Upvotes: 1
Reputation: 7207
if the parent's id is not defined or the element is nested so much that you can't count how many parents it has, i.e. get the closest parent's id that actually has an id, then this code will do the job for you: DEMO
$(document).on('click', 'a, button, [type="submit"]', function() {
if($(this).attr('id') === undefined || $(this).attr('id') === null) {
alert($(this).parents().filter(function(){
return $(this).attr('id')!=undefined && $(this).attr('id')!=null;
}).attr('id'));
} else {
alert($(this).attr('id'));
}
});
Upvotes: 1