I have this code snippet:
$('#selector1,#selector2').change(function(){
checkDate(document.getElementById($(this).attr("id")));
});
The above works fine, but I want to use jQuery’s $ instead of document.getElementById. So, I tried this but it gives me a javascript error: TypeError: valueToTest is undefined
$('#selector1,#selector2').change(function(){
checkDate($("#" + $(this).attr("id")));
});
When you call
document.getElementById('id')you get the reference to the DOM node itself, whereas calling$('#id')will return a jQuery object that has a reference to the DOM node that matched the selector (if there’s an element with the given id). With the former you can access its properties directly (this.id,this.value, etc), whereas with the second you need to use the jQuery functions (.prop(),.val(), etc).If you wanted to pass a jQuery object you’d likely also need to make changes to your
checkDatefunction to avoid errors where you’re accessing properties directly, and those properties no longer exist on the jQuery object.With that said, this line:
is far more complicated than it needs to be. You’ve already got a reference to the element –
this– so accessing itsidand passing it todocument.getElementById()to gain another reference to it makes no sense. You could simply do: