0

Trying to have jQuery access both the event.target and another element on click but receive the error:

Error: Syntax error, unrecognized expression: [object HTMLButtonElement],#element2

Selector code:

$(event.target+",#element2").closest("div").removeClass("alert-info").addClass("alert-success");

Any suggestions what I am doing wrong appreciated.

1

1 Answer 1

3

event.target isn't a selector string, it's an element. You can wrap any element in a jQuery object:

$(event.target)

So you could perform your logic on both the element and the selector:

$(event.target).closest("div").removeClass("alert-info").addClass("alert-success");
$("#element2").closest("div").removeClass("alert-info").addClass("alert-success");

Or, two reduce a little repetition, you can use .add() to combine jQuery objects into a set of objects:

$(event.target).add("#element2").closest("div").removeClass("alert-info").addClass("alert-success");
Sign up to request clarification or add additional context in comments.

1 Comment

Three, move your code to a jquery extension $.fn.alertSuccess = function(..., then $(event.target).alertSuccess();$("#element2").alertSuccess(); - optionally combine with option 2 above. See learn.jquery.com/plugins/basic-plugin-creation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.