/    Sign up×
Community /Pin to ProfileBookmark

Simple Question

HTML:
<html>
<head>
<script type=’text/javascript’ src=’sciprt.js’></script>
</head>
</html>

JS:
window.onload = init;

function init() {
var allTags = document.getElementsByTagName(“*”);
document.write(allTags.length);
}

Why would the browser output “4” when there are clearly onlyt 3 tags?
Thanks in advance….

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@felgallSep 01.2008 — Must be counting the body element that JavaScript assumes is there if you forget to add it yourself.

There are a number of elements that always appear in the DOM regardless of whether they are in the HTML or not. Another example is the tbody element inside all tables.

JavaScript reads from the DOM and not the source HTML. Where elements are mandatory in the DOM and optional in the HTML the JavaScript will see those elements even though you didn't code them.
Copy linkTweet thisAlerts:
@JavaboeyauthorSep 01.2008 — Thank you. You've just completely enlightened me on something! This has been driving me nuts all morning. I'm a complete noob, and my googling wasn't yielding any results I could understand. Thanks again.
×

Success!

Help @Javaboey spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...