The turotials online all say to access elements in javascript with document.getElementById(id). But I found I could negate this step and just type in id.attribute. I wanted to know why I didn't actually have to document.getElementById(id) my HTML attributes. Any ideas?

<!DOCTYPE html>
<html>
<body>

<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color="blue";
document.getElementById("p2").style.fontFamily="Arial";
document.getElementById("p2").style.fontSize="larger";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

Was the exact same as,

<!DOCTYPE html>
<html>
<body>

<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>

<script>
p2.style.color="blue";
p2.style.fontFamily="Arial";
p2.style.fontSize="larger";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

The second one should be invalid, since p2 isn't defined. That shouldn't work.

That is what I thought, but it works just fine. Maybe the browser saves HTML attributes and defines them. It worked on firefox and chrome though.

That's because HTML5 is the boss of his own now.

The second one should be invalid, since p2 isn't defined. That shouldn't work.

-Why would you say that?

p.s.:

<p id="p1">Hello World!</p>

This is not important, but FYI:
<P>, doesn't need an ending instruction on HTML.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.