Reputation: 476
In order to identify the element on which the user is clicking, I'm trying to use the Event Object target
.
$(document).click(function (e) {
var str = e.target.toString();
console.log(str);
if (str.indexOf("some class or id") >= 0) {
//do something
};
});
However .toString()
doesn't seem to have a useful effect on e.target
. If I do:
console.log(e.target);
I get a string which contains the beginning of the DOM element, for example <div class="myclass">
. This is needed in order to check for the presence of a substring, for example myclass
" or myid
, using indexOf
.
My purpose here is simply to identify on which div the user is clicking, by looking into event.target
for "myclass
".
Yet indexOf
will not work here, because it will return "str is not a function".
However if I try to make it into a string, as such:
console.log(e.target.toString());
I get [object HTMLDivElement]
. No trace of the HTML string I need.
How can I get the output of event.target
into a string I can manipulate?
p.s Notice how this situation is remarkably similar to this one, regarding event.target.id
: yet the proposed solutions don't work for me.
Upvotes: 3
Views: 7589
Reputation: 4475
In e.traget you have the HTML DOM element. So that, if it has an id, you should be able to do something like
var str = $(e.target).attr("id");
if(str.indexOf("id") > -1){ //do something}
Upvotes: 2
Reputation: 133403
You don't need to convert it to string. Get rid of .toString()
Directly use its ID
property.
if (e.target.id == 'myid'){
//do something
};
However if you want to valdate against selector use .is()
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
if ($(e.target).is('.myclass')){
//do something
};
Upvotes: 3