Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot get event.target into a string

Tags:

html

jquery

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.

like image 434
nonhocapito Avatar asked Jun 13 '26 06:06

nonhocapito


1 Answers

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
};
like image 83
Satpal Avatar answered Jun 15 '26 21:06

Satpal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!