Higinio Melero Higinio Melero - 3 years ago 143
HTML Question

How can i make 2 id attributes work on the same HTML element?

I have a

<input>
-element that needs 2 different id attributes. Is there a way to make it have 2 id attributes in one
<input>
? One id is for the CSS while the other id is for JavaScript.

How can i make this work? Here's an example of the code I'm trying to find a way to make it work.

<input type="button" id="button1" id="reset" value="Subscribe">


id="button1"
is for the CSS, while
id="reset"
I need for JavaScript since a click of that button will make a number above the button go up. But I need a way to clarify to it that
id="reset"
is for the JavaScript, which is on the same page as the HTML is, and the CSS is on the same page as well, obviously using the style tags.

Answer Source

Don't use more than one id-attribute on the same DOM element (its no valid HTML otherwise)! You should use another attribute for your JavaScript approach. For Example:

<input type="button" id="button1" class="jsReset" value="Subscribe">

or

<input type="button" id="button1" data-js-id="reset" value="Subscribe">

or whatever seems suitable to you.

An id in general is meant to be unique! So you should use id="button1" also only on one element at the same time as well.


Reference (w3.org)

This attribute assigns a name to an element. This name must be unique in a document.

Reference (validator.w3.org)

validating against <input type="button" id="button1" id="reset" value="Subscribe"> throws:

Error: Duplicate attribute id.


BTW: Maybe you should clarify why...

while id="reset" i need for javascript since a click of that button will make a number above the button go up

...you need another attribute than id="button1" to target your element with JavaScript. You can use

document.getElementById('button1')
jQuery('#button1') // if you already use jQuery

So I can not see why you have to add another attribute.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download