Question

Hey guys I have the following jQuery:

var $this   = $(this);
$this.closest('ul').find('li').removeClass('selected');

and I'm trying to do the same thing to an element with a similar ID by setting the variable:

var liID = $this.closest('li').attr('id');
var liID = liID.substring(0, liID.length - 1);

and then trying to call .closest('ul').find('li').removeClass('selected'); on it. I've tried this:

document.getElementById(liID).closest('ul').find('li').removeClass('selected');

and this:

liID.closest('ul').find('li').removeClass('selected');

I'm not surprised the second didn't work, but I can't figure out how to make the first one work. Any suggestions?

Was it helpful?

Solution

As you have ID, Directly use

$("#" + liID).closest('ul').find('li').removeClass('selected');

document.getElementById(liID) will return a DOM element. To use jQuery method you have to convert it into jQuery object. You may try

$(document.getElementById(liID)).closest('ul').find('li').removeClass('selected');

OTHER TIPS

document.getElementById(liID) returns a dom element reference which does not have jQuery related methods, so you need to get the jQuery object for that element to use jQuery methods.

You can use id-selector to get the target element then use the closest()

$('#'+liID).closest('ul').find('li').removeClass('selected');

document.getElementByID() return a DOM element.

To use closet you want a jquery object so wrap document.getElementByID() with $ to make it a jquery object.

It will work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top