I noticed the following:
<div id='myDiv'>...</div>
<script>
myDiv.style.color = 'red'; // I can access the object.
<script>
Before realizing this, I was always using the following:
var x = document.getElementById('myDiv');
x.style.color = 'red';
I am confused. What's the point of the second approach? Does the first approach always work?
You can't have the same id multiple times. Use class instead. Show activity on this post. COMPONENTS: if you write reusable component e.g. ) in your example then if you put two ore more components into one document then you will get INVALID html.
The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document). The id attribute is most used to point to a style in a style sheet, and by JavaScript (via the HTML DOM) to manipulate the element with the specific id.
The answer is YES!
Are IDs for an html element always available from the window object?
No. It is a non-standard Microsoft-ism that some other browsers have adopted for compatibility reasons. It is prone to namespace collisions, and not completely cross-browser compatible: don't do it.
What's the point of the second approach?
It is standard, well-supported cross-browser (and also cross-language).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With