W3Schools jQuery Quiz

2020-04-04 03:47发布

There is a jQuery quiz posted on the W3Schools site here...

http://www.w3schools.com/quiztest/quiztest.asp?qtest=jQuery

Question #19 is as follows,

Look at the following jQuery selector: $("div#intro .head").

What does it select?

A. The first element with id="head" inside any div element with class="intro"

B. All elements with class="head" inside the first div element with id="intro"

C. All div elements with id="intro" or class="head"

I got it correct by picking answer B.

My question has to do with the wording of answer B.

Shouldn't the word, "first", be removed from the answer?

B. All elements with class="head" inside the div element with id="intro"

ID is defined as "a unique identifier to an element", so not really understanding why they would refer to the "the first div element with id=intro"

I don't believe that it's intentionally trying to be tricky as all the other questions in this quiz are very straightforward.

Thank-you for your thoughts.


EDIT:

I reported this error to W3Schools and directed them to this thread.


EDIT #2:

This is another question from the same quiz.

Another questionable jQuery Quiz answer at W3Schools

2条回答
聊天终结者
2楼-- · 2020-04-04 04:40

Indeed the behavior of document.getElementById("...") is undefined if more than one element has this ID.

However, as the w3schools site consistently tries to point out, the behavior of jQuery in this situation is well-defined. If more than one element has this ID, then the first one will be selected.

No one is condoning more than one element's having a particular ID; this is still against the rules. However, unlike getElementById, jQuery has a specific reaction if this rule is broken.

查看更多
Deceive 欺骗
3楼-- · 2020-04-04 04:45

You are correct, the first language could (should) be removed from all choices.

According to the HTML 4.01 Spec:

This attribute assigns a name to an element. This name must be unique in a document.

Additionally, according to the jQuery documentation for the id selector:

Selects a single element with the given id attribute

Under the hood, the selector uses document.getElementById("..."). Interestingly, the specification for this function states:

Behavior is not defined if more than one element has this ID.

So, assuming you do have two elements with the same id, results of the function are unpredictable and browser-specific.

Sidenote: W3Schools is not regarded as one of the best places to learn JavaScript / jQuery. A well-respected alternative for JavaScript is MDC's JavaScript Guide. For jQuery, check out the tutorials page.

查看更多
登录 后发表回答