Reputation: 1774
HI all! I have a doubt. I need to get an element via its id. I know i can use document.getElementById() or jquery selector, but i don´t want to use jquery or any other library. The idea is to build a component using just js and no libraries.
I got this situation, code generated by code:
<div id="objprop">
<div id="prop-header"><span>Mi Ventana</span></div>
<div id="prop_width" style="clear: both;">
<label style="margin-left: 7px; margin-bottom: 7px; float: left;">Width</label>
<input type="text" style="float: right; margin-right: 7px; width: 70px;" id="width">
</div>
<div id="prop_height" style="clear: both;">
<label style="margin-left: 7px; margin-bottom: 7px; float: left;">Height</label>
<input type="text" style="float: right; margin-right: 7px; width: 70px;" id="height">
</div>
<div id="prop_left" style="clear: both;">
<label style="margin-left: 7px; margin-bottom: 7px; float: left;">Left</label>
<input type="text" style="float: right; margin-right: 7px; width: 70px;" id="left">
</div>
<div id="prop_top" style="clear: both;">
<label style="margin-left: 7px; margin-bottom: 7px; float: left;">Top</label>
<input type="text" style="float: right; margin-right: 7px; width: 70px;" id="top">
</div>
</div>
so, let supose i want to set the value of input width id with. I´m not sure about using document.getElementById because may be other elements with same id in the html.
well that is my doubt
Upvotes: 0
Views: 968
Reputation: 1774
thanks.
To solve my problem. i did the follow:
I create elements dynamic so i added a post fix like this: this.postfix = new Date().getTime();
so, when i have to add and input with id 'width' i add the postfix like it is named 'width_'+postfix. so i can use in a secure way document.getElementById;
Thanks
Upvotes: 0
Reputation: 103135
According to the specifications the id attribute of an element must be unique in a document. So as long as the document conforms to the specs you should have no problem using getElementById().
Upvotes: 2
Reputation: 1615
I´m not sure about using document.getElementById because may be other elements with same id in the html.
Id MUST be unique.
Upvotes: 0
Reputation: 38372
The HTML specification states that an id
must only be used once. It must be unique through-out a document. If you're dealing with valid documents, you should feel comfortable using document.getElementById()
Upvotes: 3
Reputation: 413682
The values of "id" attributes must be unique throughout the page. You're right that it would be a problem for "getElementById()" to have to deal with the same "id" value being used on multiple elements; that's why you absolutely should not do that. That's why it's called an "id" — it is the identifier for the element.
Upvotes: 1