Unpredicted behavior of using non-unique IDs - javascript

When people are saying that using identical id's for different DOM elements is wrong, I totally agree. I mean, there is no even something to discuss.
But what is actually meant by the phrase "if you will have several eponymous ids on the page, that doesn't guaranteed to work"?
What actually does not guaranteed to work? We can treat ID as a regular attribute, thus, we can find all divs that document.querySelectorAll('[id="container"]'). Accessing through getAttribute/setAttribute should work as well. If we are trying to fetch an element via document.getElementById - well, I haven't tested, but most probably selector engine will return first element it find traversing the tree. I can imagine this can not be guaranteed. What else?
CSS will work pretty fine - #container {background-color: "red"} will paint with red all found containers (or am I wrong). Can somebody show me where in standard spec such behaviour is not guaranteed?
So, what is actually not guaranteed? Once again, I do acknowledge the fact that using same IDs is wrong. Neither do I want discuss perfomance issues of applying id-heavy css rules. The question is about something which is quite similar to what C/C++ programmers call "unpredicted behavior".
UPD: If it sounds hard or even stupid for you, then well, just provide an examples of unpredictable ID related behavior in specific browser. At least, as for me, it is more useful answer than "well, anything is not guaranteed, how can not you get it!".

An implementation would be within the spec if it refused completely to work with documents that contain duplicate ids, or ignored the multiply-used id in all of the elements that claim it, or returned a random of the elements from getElementById. It could even be a different random element in each call.
Can somebody show me where in standard spec such behaviour is not guaranteed?
That's not how it works. If it's not guaranteed, then everywhere in the spec is where it's not guaranteed. It's only guaranteed if somewhere in the spec there's an explicit guarantee you can point to. Otherwise, there's no guarantee in the spec, which means that it's not guaranteed.

The spec says that ID's are supposed to be unique.
That means that the browser itself has no obligation to implement code that can support multiple non-unquie IDs. It can assume when it builds the DOM model that ids are unique and are usable as keys. They may work in some browsers, today. But maybe tomorrow they won't. Just because they happen to function in the browsers you have tested, doesn't mean they will in future versions, or they behave as such in a different non-repeatable manner.
Maybe the first time you load a page on a monday document.getElementById might return the first element, if it's after 5pm on a tuesday and it's on an SSL site, then maybe document.getElementById throws an exception. Maybe a new release of firefox doesn't apply css attributes to anything past the first occurance of the id. Who knows. The browser developers don't have to care, that is what "not guaranteed to work" means.

Here is a jsfiddle showing some selector quirks: http://jsfiddle.net/DmEmJ/
Quoth the spec:
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.
If you want a non-unique handle, use classes. That's what they are for.

Related

Ajax code only working on the first link clicked [duplicate]

I am using jQuery and I am just wondering, does ID have to be always unique in the whole page? Class, I know, can be repeated as many times as you like, what about ID?
Yes, it must be unique.
HTML4:
https://www.w3.org/TR/html4/struct/global.html#h-7.5.2
Section 7.5.2:
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.
HTML5:
https://www.w3.org/TR/html5/dom.html#element-attrdef-global-id
The id attribute specifies its element's unique identifier (ID). The
value must be unique amongst all the IDs in the element's home subtree
and must contain at least one character. The value must not contain
any space characters.
Does an ID have to be unique in the whole page?
No.
Because the HTML Living Standard of March 15, 2022, clearly states:
The class, id, and slot attributes may be specified on all HTML elements. …….
When specified on HTML elements, the id attribute value must be unique amongst all the IDs in the element’s tree and must contain at least one character. The value must not contain any ASCII whitespace.
and a page may have several DOM trees. It does, for example, when you’ve attached (Element.attachShadow()) a shadow DOM tree to an element.
TL; DR
Does an ID have to be unique in the whole page?
No.
Does an ID have to be unique in a DOM tree?
Yes.
from mdn
https://developer.mozilla.org/en/DOM/element.id
so i guess it better be...
Technically, by HTML5 standards ID must be unique on the page - https://developer.mozilla.org/en/DOM/element.id
But I've worked on extremely modular websites, where this is completely ignored and it works. And it makes sense - the most surprising part.
We call it "componentization"
For example, you might have a component on your page, which is some kind of widget. It has stuff inside with their own unique IDs eg "ok-button"
Once there are many of these widgets on the page, you technically have invalid HTML. But it makes perfect sense to componentize your widgets so that they each, internally, reference their own ok button eg if using jquery to search from it's own root it might be: $widgetRoot.find("#ok-button")
This works for us, though technically IDs shouldn't be used at all, once they're not unique.
As cited above, even YouTube does it, so it's not so renegade.
Jan 2018, here is Youtube HTML , you can see id="button" id="info" are duplicated.
That's basically the whole point of an ID. :) IDs are specific, can only be used once per page. Classes can be used as pleased.
Browsers used to be lenient on this (many years ago when css was young) and allow the ID to be used more than once. They have become more strict.
However, yes ID's are to be unique and only used once.
If you need to use css formatting more than once use CLASS.
With Javascript, you can only reference to one element using ID. document.getElementById and jQuery's $ selector will return only the first element matching. So it doesn't make sense using the same ID on multiple elements.
There are great answers for the same question at https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really.
One tidbit not mentioned above is that if there are several identical ids one the same page (which happens, even though it violates the standard):
If you have to work around this (that's sad), you can use $("*#foo") which will convince jQuery to use getElementsByTagName and return a list of all matched elements.
Yes, IDs are unique. Class are not.
IDs always have to be unique.
Everybody has a unique identification number (ex. Social Security number), and there are lots of people in a social class
I'm adding to this question, because I feel it has not been answered adequately in any of the above,
As a point reference: I've implemented non-unique id's, and all works just fine (across all browsers). Importantly, when coding, I've not run into any css logic errors, which is where the rubber hits the road (IMO) on this question. Have also not run into any conflicts in js (as one can glean out id's in context with classes)
So, why do id's have to be unique? Obvious answer (as stated and re-stated above) is 'cause the 'standards' say so. The missing part for me is why?
i.e. what actually goes awry (or could theoretically go awry) if (heaven forbid) someone inadvertently used the same id twice?
The reference with all browsers these days?
Makes div possible in such terms of being used multiple times.
There is no rule that it must be unique. When all browsers understand:
<script>div#some {font-size: 20px}</script>
<div id="some"><p>understand</p></div>
<div id="some"><h1>me too</h1></div>
When you add new style CSS codes you have the possibility to use the addition of styles. Since that even is not supposed to be unique it describes the opposite use, so make more styles but do not make more objects? And as you can; assign several div objects, so why didn't they tell you that class must be unique? That's because the class does not need unique value. And that makes the ID in legal terms obsolete if not being unique.
<script>.some {font-size: 25px}</script>
<div class="some"><p>enter</p></div>
<div class="some"><h1>enter</p></div>
"When there is no rule when a rule is said. Then the rule is not fulfilled. It's not inherent to exist. By only in the illusion of all rules that it should have existed only to make life much harder."
Just because some people say div must be unique, this might be right, but at least through their professional perspective to say it, they have to say it. Unless they didn't check the modern browsers, which from nearly the beginning were able to understand the code of several different div objects with the same style.
ID must be unique - One reason for that is, that in the Browser-JavaScript-Context exists a methode: Document.getElementById()
This method can only return one element.
If a Document has not unique IDs, this function behaves in an undocumented and unforeseeable way.
I think, this is reason enough to only use one ID per Document.
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

How to add a <tr> so that the tasks can be shown 1 after the other in a JS/CSS/HTML To-Do List? [duplicate]

Under what circumstances is it illegal for an HTML page to contain elements with duplicate ID attributes?
As a developer who has worked with HTML for many years, I am aware that the intention is that element ids should be unique - what I am asking is for the practical negative effects of duplicate ids.
Granted, getElementByID()-like functions in some libraries might return arrays rather than a single element and this could cause issues when the developer had not anticipated this case. However, as far as I know, such functions will continue to operate so clearly they are not a breaking-effect of id duplicates.
So why is it that duplicate ids are said to be not allowed?
EDIT: The driver for the question was that I saw some templating libraries when generating list/repeated items, producing elements with duplicate ids and I wondered what the impact of that might be in practical terms and how to decide whether to adopt those libraries.
I also wondered about the effect of modal plugins, or any other, that might clone an existing hidden node and thereby create a duplicate via code, and then what the browser would do in that case.
It's always "illegal". Against the spec = illegal. Just because something "seems to work" due to a fluke or overly generous compiler doesn't mean it is valid code.
Another way to think about it: juhst becuse u kan reed ths duzint mayke it korrect Englesh. You have a generous compiler/brain which can understand that (e.g Google Chrome), but someone with more limited English knowledge (e.g. new to the market Browser X) or someone with a mental incapacity (e.g. Internet Explorer) might not understand it at all...but would be able to understand it if each word was spelled correctly/according to spec.
https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really
A few reasons I can find:
According to the DOM spec, "If more than one element has an ID attribute with that value, what is returned is undefined"
And:
Incorrect doesn't come in shades of grey. This code violates the standard and is therefore incorrect. It would fail validation checking, and it should. That said, no browser currently on the market would complain about it, or have any problem with it at all. Browsers would be within their rights to complain about it, but none of the current versions of any of them currently do. Which doesn't mean future versions might not treat this code badly.
And:
Behavior trying to use that ID as a selector, either in css or javascript, is unguessable and probably varies from browser to browser.
And:
Many javascript libraries will not work as expected
And:
Experience says that getElementById in major browsers will return the first matched element in the document. But this may not always be the case in the future.
Specification says UNIQUE
HTML 4.01 specification says ID must be document-wide unique.
HTML 5 specification says the same thing but in other words. It
says that ID must be unique in its home subtree, which is basically
the document if we read the definition of it.
Avoid duplication
But since HTML renderers are very forgiving when it comes to HTML
rendering they permit duplicate IDs. This should be avoided if at all
possible and strictly avoided when programmatically accessing
elements by IDs in JavaScript. I'm not sure what getElementById
function should return when several matching elements are found?
Should it:
return an error?
return first matching element?
return last matching element?
return a set of matching elements?
return nothing?
But even if browsers work reliably these days, nobody can guarantee
this behavior in the future since this is against specification.
That's why I recommend you never duplicate IDs within the same
document.
This is an answer by Robert Koritnik at Software Engineering asked by danludwig
Question: Two HTML elements with same id attribute: How bad is it really?
Duplicate ids not allowed in HTML
That code is incorrect. Incorrect doesn't come in shades of grey. This
code violates the standard and is therefore incorrect. It would fail
validation checking, and it should. That said, no browser currently
on the market would complain about it, or have any problem with it at
all. Browsers would be within their rights o complain about it, but
none of the current versions of any of them currently do. Which
doesn't mean future versions might not treat this code badly.
~From Dan Ray
Duplicate ids and JavaScript
So if you use duplicate ids in your HTML many libraries will not work as expected. The most libraries will get the first id they find and return that element. When we look at pure JavaScript: the document.getElementById("idName"); should return in the case of multiple elements with the same id. It says it must return the first element, in tree order.
Under what circumstances is it illegal for an HTML page to contain
elements with duplicate ID attributes?
It is illegal in any circumstances as per the specification:
When specified on HTML elements, the id attribute value must be unique amongst all the IDs in the element's tree [...].
As a developer who has worked with HTML for many years, I am aware
that the intention is that element ids should be unique - what I am
asking is for the practical negative effects of duplicate ids.
The CSS selector specification does not define how to handle documents with non-unique ids, as far as I can tell. So you cannot safely use id selectors in CSS in those cases.
The id attribute is also used to navigate to fragments (aka "anchors"). According to the specification, the browser should navigate to the "first such element in tree order". But that might conflict with which element actually comes first from top to bottom. I.e. your layout could conflict with the actual fragment link.
Granted, getElementByID() style functions in jquery etc might return
arrays rather than a single element and this could cause issues when
the developer had not anticipated this case. However, as far as I
know, such functions will continue to operate so clearly they are not
a breaking-effect of id duplicates.
That is clearly wrong, getElementByID() never returns an array. As per the specification:
The getElementById(elementId) method, when invoked, must return the first element, in tree order, within context object’s descendants, whose ID is elementId, and null if there is no such element otherwise.
Your expectation is also wrong in the case of jQuery:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
There is really no reason to violate the specification in this case, you don't gain anything by doing it. While your pages won't completely break, you could run into problems with CSS, fragment links, and probably other things. In addition, your documents will be invalid and duplicate ids might confuse other people that have to maintain your code.

Jquery html function not working properly until remove called [duplicate]

I am using jQuery and I am just wondering, does ID have to be always unique in the whole page? Class, I know, can be repeated as many times as you like, what about ID?
Yes, it must be unique.
HTML4:
https://www.w3.org/TR/html4/struct/global.html#h-7.5.2
Section 7.5.2:
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.
HTML5:
https://www.w3.org/TR/html5/dom.html#element-attrdef-global-id
The id attribute specifies its element's unique identifier (ID). The
value must be unique amongst all the IDs in the element's home subtree
and must contain at least one character. The value must not contain
any space characters.
Does an ID have to be unique in the whole page?
No.
Because the HTML Living Standard of March 15, 2022, clearly states:
The class, id, and slot attributes may be specified on all HTML elements. …….
When specified on HTML elements, the id attribute value must be unique amongst all the IDs in the element’s tree and must contain at least one character. The value must not contain any ASCII whitespace.
and a page may have several DOM trees. It does, for example, when you’ve attached (Element.attachShadow()) a shadow DOM tree to an element.
TL; DR
Does an ID have to be unique in the whole page?
No.
Does an ID have to be unique in a DOM tree?
Yes.
from mdn
https://developer.mozilla.org/en/DOM/element.id
so i guess it better be...
Technically, by HTML5 standards ID must be unique on the page - https://developer.mozilla.org/en/DOM/element.id
But I've worked on extremely modular websites, where this is completely ignored and it works. And it makes sense - the most surprising part.
We call it "componentization"
For example, you might have a component on your page, which is some kind of widget. It has stuff inside with their own unique IDs eg "ok-button"
Once there are many of these widgets on the page, you technically have invalid HTML. But it makes perfect sense to componentize your widgets so that they each, internally, reference their own ok button eg if using jquery to search from it's own root it might be: $widgetRoot.find("#ok-button")
This works for us, though technically IDs shouldn't be used at all, once they're not unique.
As cited above, even YouTube does it, so it's not so renegade.
Jan 2018, here is Youtube HTML , you can see id="button" id="info" are duplicated.
That's basically the whole point of an ID. :) IDs are specific, can only be used once per page. Classes can be used as pleased.
Browsers used to be lenient on this (many years ago when css was young) and allow the ID to be used more than once. They have become more strict.
However, yes ID's are to be unique and only used once.
If you need to use css formatting more than once use CLASS.
With Javascript, you can only reference to one element using ID. document.getElementById and jQuery's $ selector will return only the first element matching. So it doesn't make sense using the same ID on multiple elements.
There are great answers for the same question at https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really.
One tidbit not mentioned above is that if there are several identical ids one the same page (which happens, even though it violates the standard):
If you have to work around this (that's sad), you can use $("*#foo") which will convince jQuery to use getElementsByTagName and return a list of all matched elements.
Yes, IDs are unique. Class are not.
IDs always have to be unique.
Everybody has a unique identification number (ex. Social Security number), and there are lots of people in a social class
I'm adding to this question, because I feel it has not been answered adequately in any of the above,
As a point reference: I've implemented non-unique id's, and all works just fine (across all browsers). Importantly, when coding, I've not run into any css logic errors, which is where the rubber hits the road (IMO) on this question. Have also not run into any conflicts in js (as one can glean out id's in context with classes)
So, why do id's have to be unique? Obvious answer (as stated and re-stated above) is 'cause the 'standards' say so. The missing part for me is why?
i.e. what actually goes awry (or could theoretically go awry) if (heaven forbid) someone inadvertently used the same id twice?
The reference with all browsers these days?
Makes div possible in such terms of being used multiple times.
There is no rule that it must be unique. When all browsers understand:
<script>div#some {font-size: 20px}</script>
<div id="some"><p>understand</p></div>
<div id="some"><h1>me too</h1></div>
When you add new style CSS codes you have the possibility to use the addition of styles. Since that even is not supposed to be unique it describes the opposite use, so make more styles but do not make more objects? And as you can; assign several div objects, so why didn't they tell you that class must be unique? That's because the class does not need unique value. And that makes the ID in legal terms obsolete if not being unique.
<script>.some {font-size: 25px}</script>
<div class="some"><p>enter</p></div>
<div class="some"><h1>enter</p></div>
"When there is no rule when a rule is said. Then the rule is not fulfilled. It's not inherent to exist. By only in the illusion of all rules that it should have existed only to make life much harder."
Just because some people say div must be unique, this might be right, but at least through their professional perspective to say it, they have to say it. Unless they didn't check the modern browsers, which from nearly the beginning were able to understand the code of several different div objects with the same style.
ID must be unique - One reason for that is, that in the Browser-JavaScript-Context exists a methode: Document.getElementById()
This method can only return one element.
If a Document has not unique IDs, this function behaves in an undocumented and unforeseeable way.
I think, this is reason enough to only use one ID per Document.
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

show mysql query in modal popup [duplicate]

I am using jQuery and I am just wondering, does ID have to be always unique in the whole page? Class, I know, can be repeated as many times as you like, what about ID?
Yes, it must be unique.
HTML4:
https://www.w3.org/TR/html4/struct/global.html#h-7.5.2
Section 7.5.2:
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.
HTML5:
https://www.w3.org/TR/html5/dom.html#element-attrdef-global-id
The id attribute specifies its element's unique identifier (ID). The
value must be unique amongst all the IDs in the element's home subtree
and must contain at least one character. The value must not contain
any space characters.
Does an ID have to be unique in the whole page?
No.
Because the HTML Living Standard of March 15, 2022, clearly states:
The class, id, and slot attributes may be specified on all HTML elements. …….
When specified on HTML elements, the id attribute value must be unique amongst all the IDs in the element’s tree and must contain at least one character. The value must not contain any ASCII whitespace.
and a page may have several DOM trees. It does, for example, when you’ve attached (Element.attachShadow()) a shadow DOM tree to an element.
TL; DR
Does an ID have to be unique in the whole page?
No.
Does an ID have to be unique in a DOM tree?
Yes.
from mdn
https://developer.mozilla.org/en/DOM/element.id
so i guess it better be...
Technically, by HTML5 standards ID must be unique on the page - https://developer.mozilla.org/en/DOM/element.id
But I've worked on extremely modular websites, where this is completely ignored and it works. And it makes sense - the most surprising part.
We call it "componentization"
For example, you might have a component on your page, which is some kind of widget. It has stuff inside with their own unique IDs eg "ok-button"
Once there are many of these widgets on the page, you technically have invalid HTML. But it makes perfect sense to componentize your widgets so that they each, internally, reference their own ok button eg if using jquery to search from it's own root it might be: $widgetRoot.find("#ok-button")
This works for us, though technically IDs shouldn't be used at all, once they're not unique.
As cited above, even YouTube does it, so it's not so renegade.
Jan 2018, here is Youtube HTML , you can see id="button" id="info" are duplicated.
That's basically the whole point of an ID. :) IDs are specific, can only be used once per page. Classes can be used as pleased.
Browsers used to be lenient on this (many years ago when css was young) and allow the ID to be used more than once. They have become more strict.
However, yes ID's are to be unique and only used once.
If you need to use css formatting more than once use CLASS.
With Javascript, you can only reference to one element using ID. document.getElementById and jQuery's $ selector will return only the first element matching. So it doesn't make sense using the same ID on multiple elements.
There are great answers for the same question at https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really.
One tidbit not mentioned above is that if there are several identical ids one the same page (which happens, even though it violates the standard):
If you have to work around this (that's sad), you can use $("*#foo") which will convince jQuery to use getElementsByTagName and return a list of all matched elements.
Yes, IDs are unique. Class are not.
IDs always have to be unique.
Everybody has a unique identification number (ex. Social Security number), and there are lots of people in a social class
I'm adding to this question, because I feel it has not been answered adequately in any of the above,
As a point reference: I've implemented non-unique id's, and all works just fine (across all browsers). Importantly, when coding, I've not run into any css logic errors, which is where the rubber hits the road (IMO) on this question. Have also not run into any conflicts in js (as one can glean out id's in context with classes)
So, why do id's have to be unique? Obvious answer (as stated and re-stated above) is 'cause the 'standards' say so. The missing part for me is why?
i.e. what actually goes awry (or could theoretically go awry) if (heaven forbid) someone inadvertently used the same id twice?
The reference with all browsers these days?
Makes div possible in such terms of being used multiple times.
There is no rule that it must be unique. When all browsers understand:
<script>div#some {font-size: 20px}</script>
<div id="some"><p>understand</p></div>
<div id="some"><h1>me too</h1></div>
When you add new style CSS codes you have the possibility to use the addition of styles. Since that even is not supposed to be unique it describes the opposite use, so make more styles but do not make more objects? And as you can; assign several div objects, so why didn't they tell you that class must be unique? That's because the class does not need unique value. And that makes the ID in legal terms obsolete if not being unique.
<script>.some {font-size: 25px}</script>
<div class="some"><p>enter</p></div>
<div class="some"><h1>enter</p></div>
"When there is no rule when a rule is said. Then the rule is not fulfilled. It's not inherent to exist. By only in the illusion of all rules that it should have existed only to make life much harder."
Just because some people say div must be unique, this might be right, but at least through their professional perspective to say it, they have to say it. Unless they didn't check the modern browsers, which from nearly the beginning were able to understand the code of several different div objects with the same style.
ID must be unique - One reason for that is, that in the Browser-JavaScript-Context exists a methode: Document.getElementById()
This method can only return one element.
If a Document has not unique IDs, this function behaves in an undocumented and unforeseeable way.
I think, this is reason enough to only use one ID per Document.
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

Why $('div#my') is returning Object Reference instead of HTML Tag? [duplicate]

This question already has an answer here:
Why sometimes jQuery selector returns something like "a.fn.init"? [closed]
(1 answer)
Closed 6 years ago.
I don't know what happen to my Chrome browser, but all of sudden the behavior of doing $('div#my') in console is totally different from before. One time I've experienced this but later it somehow recovered, so I don't know how to reproduce it, and today it happened again.
Please watch the video:http://peaceevertvimg.org/jq.php.
In the video I do $('div#my') in two different browsers:
the first browser is not chrome but I believe it imitates Chrome so its behavior is what I expect and what I have almost always been experienced. Because currently my chrome is not working as expected so I have to use it to demonstrate my expection: when you do $('div#my)` you see directly the html TAG, and you can easily see the tag's html content, which is "something" in this case.
In contrast, in my chrome browser, the result is different, when I do $('div#my') I see an Object(n.fn.init), and I can't see the "something" immediately, which of course is very inconvenient. But before, I am pretty sure it was not like this, the behavior WAS exactly like that in the first browser.
The simple webpage in this video is http://peaceevertvimg.org/jquery.php, you can go test for yourself in chrome browser. And I am pretty sure most of you will see the first behavior. What happened to my chrome?(I've disabled all expansions and updated it to the latest version)
By the way, is "HTML Tag" and "Object Reference" the right words to describe these two different outcome?
*************Update*************
If the video is not sufficient to understand what I ask and what I want to fix, these two pictures may help.
Picture#1: This is the "normal" behavior I've expected:
Picture#2: This is the current behavior I am experiencing:
You can see the big differences, the first one is much more intuitive, revealing key information immediately, while the 2nd one is not, at least to me. What causes this problem and how do I go back to the first one?
$('div#my') doesn't return a DOM reference. It returns a jQuery wrapper around the found elements.
$('div#my')[0] would return a DOM reference. Or, forget jQuery and use:
document.getElementById("my");
...and you will get a DOM reference directly
Also, since there should/will only ever be one element with a given ID, it is unnecessary to use div#my, just use #my.
Assuming we have a <div id=someDiv>, and then we write:
console.log($("#someDiv"));
console.log($("#someDiv")[0]);
Chrome shows this:
In the first log, we see that the result is a jQuery object that contains one element (the div). In the second, we see the element directly.
Now, depending on what version of Chrome you have, you may see the first one reported simply as [Object object], but that doesn't change the underlying result.
From: Devx (http://www.devx.com/codemag/Article/40923)
Selectors let you select DOM elements so that you can apply
functionality to them with jQuery's operational methods. jQuery uses a
CSS 3.0 syntax (plus some extensions) to select single or multiple
elements in a document. You're probably already familiar with the CSS
syntax from HTML styling. Even if you're not, it's fairly easy to pick
up the key CSS selector features. I'll go as far as saying that jQuery
is the reason I really started to grok CSS. Using CSS syntax you can
select elements by ID, CSS class, attribute filters, or by their
relationship to other elements. You can even chain filter conditions
together. Look at this simple example, which selects all second-column
TD elements in a table using a simple selector: $("#gdEntries
td:nth-child(2)").
The jQuery Object: The Wrapped Set: Selectors return a jQuery object
known as the "wrapped set," which is an array-like structure that
contains all the selected DOM elements. You can iterate over the
wrapped set like an array or access individual elements via the
indexer ($(sel)[0] for example). More importantly, you can also apply
jQuery functions against all the selected elements. - See more at:
http://www.devx.com/codemag/Article/40923#sthash.l8Mo8CbH.dpuf
What you are seeing is said jQuery object returned by jQuery.fn.init().
What is going on is that jQuery() is being defined as jQuery.fn.init() which is another way to say jQuery.prototype.init() which is the selector function! What this means is that no one would call jQuery.fn.init() or jQuery.init() because jQuery() IS .init().
Some more info and a look at the jQuery code here: Help understanding jQuery's jQuery.fn.init Why is init in fn
As for a solution to your problem: https://chrome.google.com/webstore/detail/jquery-console-fix/jlmkkpkcgomkdpfhgjlpaaonhafnjgob?hl=en

Categories

Resources