Thursday, March 22, 2018

jQuery $() vs. document.getElementByID -- differences











More jQuery newbieisms to inflict on you folks...



I have some code that is using jQuery more or less happily. My confusion is that, in one case, I get my hands on an identifier which is the ID of a div on the page. I expect that $(theIdentifier) will get its hands on the object, but it doesn't; console.log returns 'undefined'. However, document.getElementById(theIdentifier) succeeds -- it returns the thing I'm looking for, and further operations on the div work as expected.




What's up here? Shouldn't they be identical? Why isn't the jQuery version working?



Puzzled, obviously; thanks for any advice!


Answer



The argument to "$()" has to be a selector:



var $thing = $("#" + thingId);


That's almost the same as calling "getElementById()". The difference is that the latter will only care about "id" values (except in IE, see below), while the jQuery selector-based code will pay attention to embedded CSS metacharacters. Thus, if you've got an "id" value with a "." in it, like this:




var foo = $('#thing.special');


then that will look for an element with id "thing" and class "special", instead of an element with the id "thing.special".



The thing with IE: for reasons known only to some mysterious developers at Microsoft, the "getElementById()" code in IE will return elements whose "name" attribute matches the argument. That behavior is not dependent on the presence of an element with the same "id" value; I think it returns the first one it finds in the DOM. (I don't know about IE9 in this regard.)



Note — a comment mentions correctly that the "$()" function can take a variety of different types of arguments, resulting in a variety of effects. When I said it "has to be a selector", I was referring to its use with string-valued arguments.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...