You are here: Reference > JavaScript > client-side > HTML DOM > properties > htmlFor (script)

htmlFor property (script)

Browser support:
Sets or retrieves the identifier of the element to which the script is bound when a specific event is fired for the element.
Use it together with the event property that specifies the type of the event to listen for. For a cross-browser solution use inline event attributes. See Example 2 for details.
If you want to add event listeners dynamically use the addEventListener or attachEvent methods.

Syntax:

object.htmlFor;
You can find the related objects in the Supported by objects section below.
This property is read/write.
HTML page for this property: for

Possible values:

String that sets or retrieves the identifier of an element.
Default: this property has no default value.

Example HTML code 1:

This example illustrates the use of the for attribute:
<head>
    <script type="text/javascript" for="myButton" event="onclick">
        alert ("You have clicked on the button.");
    </script>
</head>
<body>
    <button id="myButton">Sample button</button>
</body>
Did you find this example helpful? yes no

Example HTML code 2:

This example is equivalent to the previous one, but it uses inline event handling to listen for the event:
<head>
    <script type="text/javascript">
        function OnButtonClick () {
            alert ("You have clicked on the button.");
        }
    </script>
</head>
<body>
    <button onclick="OnButtonClick ();">Sample button</button>
</body>
Did you find this example helpful? yes no

Example HTML code 3:

This example illustrates the use of the for attribute and the htmlFor property:
<head>
    <script type="text/javascript" id="myScript" for="button1" event="onclick">
        var scriptTag = document.getElementById ("myScript");
        scriptTag.htmlFor = (scriptTag.htmlFor == "button1")? "button2" : "button1";
        alert ("Now the script is attached to the element with id:" + scriptTag.htmlFor);
    </script>
</head>
<body>
    <button id="button1">Listen the onclick event on the other button</button>
    <br />

    <button id="button2">Listen the onclick event on the other button</button>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content