function toggleClassDoneOnAndOff(event) {
if (event.target.tagName === "LI") {
event.target.classList.toggle("done");
}
}
ul.addEventListener("click", toggleClassDoneOnAndOff);
Can anyone explain why LI need to be in caps?
I just try to find the answer but dont understand the explanation
3
Answers
According to Element: tagName property documentation:
because behind HTML, all its elements are described in an object model, directly accessible in javascript. To simplify [a lot] all HTML objects are described in javascript, whose particularity is to be case sensitive. therefore the prototype of a UL element has always been capitalized.
In reality, the first html browser is written in C, which is also case sensitive (see Robert Cailliau -> first web browser MacWWW)
You can also use a generic method matches() which uses css syntax where lowercase is accepted:
in comments:
see in
console.log( document.querySelector('li'))
(Firefox)tagName will return an uppercase value
see HTML Element prototype… (HTML LI Element prototype is herited from HTML Element prototype)
herited from Dom Element…
the tagName value comes from a get method.
Then you would have to look at source codes of the javascript engines (SpiderMonkey for firefox) to check where this value really comes from in capital letters, but we already have a clue: the name of the HTMLLIElementprototype prototype does indeed contain the value
LI
in capital letters; and I’m willing to bet a bunch of peanuts that there’s a connection between those uppercase letters and the value returned by theget tagName()
.It’s simple: the
tagName
property is defined to always be in all-caps, and===
(and==
for that matter) compares strings exactly;'a' === 'A'
is false.You could do the comparison other ways; Mister Jojo in their answer suggests calling the
matches
method on the target rather than using itstagName
property at all. But you could still usetagName
, and just explicitly convert to lowercase:That’s doing extra work, though. Seems easier to just use the all-caps version, since that’s guaranteed to be what
.tagName
contains.