Reputation: 495
In order to check the working of the DOM tree (actually to check how it works if I don't put the tags orderly or write random text without using any tag) I touched upon the LIVE DOM viewer.
As I write a title before a text, DOM tree shows it in the HEAD section just the right way:
input:
<!DOCTYPE html>
<title>XYZ</title>
random text
Output(what the DOM viewer shows):
DOCTYPE: html
HTML
HEAD
TITLE
#text: XYZ
#text:
BODY
#text: random text
but when I write a text before the title tag, it shows the title in the BODY section and not in HEAD. Why is that happening? :
input:
<!DOCTYPE html>
random text
<title>XYZ</title>
output:
DOCTYPE: html
HTML
HEAD
BODY
#text: random text
TITLE
#text: XYZ
#text:
Upvotes: 1
Views: 259
Reputation: 288480
Basically, when the parser sees some text directly inside the head, the insertion mode is switched to "in body", so the text appears inside the body
elements. Following title
elements won't be moved to the head
, because it has already been completely parsed.
Specifically, this code ...
<!DOCTYPE html>
<title>XYZ</title>
random text
... is parsed as follows:
<title>
start tag. An html
element is created. The insertion mode is switched to "before head", and the token is reprocessed.<title>
start tag. A head
start tag is inserted. The insertion mode is switched to "in head", and the token is reprocessed.<title>
start tag. The generic RCDATA element parsing algorithm is followed.title
element is inserted. The insertion mode is switched to "text".</title>
end tag. The title
element is popped off the stack of open elements. The insertion mode is switched to the original one.head
element is popped off the stack of open elements. The insertion mode is switched to "after head", and the token is reprocessed.body
start tag is inserted. The insertion mode is switched to "in body", and the token is reprocessed.And this code ...
<!DOCTYPE html>
random text
<title>XYZ</title>
... is parsed as follows:
html
element is created. The insertion mode is switched to "before head", and the token is reprocessed.head
start tag is inserted. The insertion mode is switched to "in head", and the token is reprocessed.head
element is popped off the stack of open elements. The insertion mode is switched to "after head", and the token is reprocessed.body
start tag is inserted. The insertion mode is switched to "in body", and the token is reprocessed.<title>
start tag. The token is processed using "in head" insertion mode.<title>
start tag. The generic RCDATA element parsing algorithm is followed.title
element is inserted. The insertion mode is switched to "text".</title>
end tag. The title
element is popped off the stack of open elements. The insertion mode is switched to the original one.Upvotes: 1