1

I do believe this is a very stupid question and there's a very simple answer for it, but I didn't found a solution:

I have the following JavaScript function:

function setStatus(order, operation, status, elem){
    elem.parent().$(".active").removeClass("active");
    elem.addClass("active");
}

Elem is Image-element in my HTML which I'm sure is the right one by checking it's type with alert(elem);

The error I get is exactly what I expected:

Object #< HTMLImageElement> has no method 'parent'

I already know this is because elem is a DOM-element and not an JQuery-element which means that it's not possible to use functions like parent() and addClass(). How can I use all JQuery-function on my elem? Is there a way to convert a DOM-element to a JQuery-element? I found this question on the internet many times with this that should have been $(this), but $(elem) doesn't seem to work.

3
  • $(elem).siblings().removeClass("active").end().addClass("active");...? Commented Apr 22, 2013 at 7:58
  • why are you using $(".active") ? Commented Apr 22, 2013 at 7:58
  • $(".active", $(elem).parent()).removeClass("active"); $(elem).addClass("active"); alert() isn't the best way to log/debug code. Use instead console.log($(elem)); Commented Apr 22, 2013 at 8:01

4 Answers 4

2

Try

function setStatus(order, operation, status, elem){
    elem.parent().find(".active").removeClass("active");
    elem.addClass("active");
}
Sign up to request clarification or add additional context in comments.

Comments

2

try this

$(elem).parent().removeClass("active");
 $(elem).addClass("active");

remove $(".active"). i think this is also culprit.

4 Comments

that does the trick! But how must I remove al "actives" from the elements with classname active now?
$(".active").removeClass("active"); add this line at the start of code. ghope it will work
well, that's not quite the same as I wanted to do, the function has to remove all "actives" from the elements with classname active in the parent of elem. Your code will remove "active" the parent, not for the elements WITHIN parent
i was on lunch... i am glad you find your answer :)
1

.parent() is a jquery function so in order to use it, you must "jqueryify" the element you are working with, so:

$(elem)

also, the spurious $('.active') would cause issues so the solution should be:

$(elem).parent().removeClass("active");

However, without seeing some HTML to go along with the JS, I can't be 100% sure.

Comments

0

You have some syntax errors in your script and you can use this .addback() to chain it.

elem.parent(".active").removeClass("active").addBack().addClass("active");

Comments

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.