Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are IDs for an html element always available from the window object? [duplicate]

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?

like image 548
Zo72 Avatar asked Apr 02 '13 15:04

Zo72


People also ask

Can you have duplicate ids in HTML?

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.

Can two HTML elements have the same ID?

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.

Are IDS unique in HTML?

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.

Are HTML IDS Global?

The answer is YES!


1 Answers

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).

like image 163
Quentin Avatar answered Oct 02 '22 19:10

Quentin