/    Sign up×
Community /Pin to ProfileBookmark

Easy Loop Question

I’m a noob and apparently a complete idiot. Here’s my very-stripped-down HTML:

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

Now here is my very-stripped-down javascript:

window.onload = init;

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

Here is what I get in my browser:

43

From what I can tell, there should be 3 tags: <html><head><script>. There’s nothing more on the page. The first output it writes is “4”. How is it counting 4 tags when there are only 3? Secondly, I ask it to output the same thing again, and it gives the answer of “3”. Why is the length of allTags changing from 4 to 3 with nothing else being down in the script? I’ve also tried adding tags in the HTML. It makes the first number go up, but the second output is always three? I have no idea what’s going on here. Any ideas?

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@TaboSep 01.2008 — alltags is an array.

[CODE]
for(var i=0;i<alltags.length;i++){
document.write(alltags[i]);
}
[/CODE]


43 is the number of tags in the array (the arrays length).

Using document.write [B]after [/B]a page has loaded will write over that page, forming a new page with what was specified within the brackets.
Copy linkTweet thisAlerts:
@JavaboeyauthorSep 01.2008 — But how about this. Using the same HTML above and just this JavaScript:

window.onload = init;

function init() {

var allTags = document.getElementsByTagName("*");

document.write(allTags.length);

}

Why would this be returning "4" when there are clearly only 3 tags?
Copy linkTweet thisAlerts:
@Declan1991Sep 01.2008 — Just because you don't define a body, doesn't mean it's not there.
×

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 5.18,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

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

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...