Skip to content Skip to sidebar Skip to footer

Html/javascript: Add Attribute To An Html Control

Need: Find a way to add a valid tag/attribute/property to a normal html control. What I have is some javascript/jquery adding a click event to a link that will show or hide a div.

Solution 1:

If you're using JQuery, just get and set the attributes with .attr().

Get: this.attr("textToShow")

Set: this.attr("textToShow", value)

Solution 2:

The way you add an attribute to an html control is by using the element.setAttribute("attributeName", "attributeValue") where "element" is the element you want to add the attribute to.

To get an attribute you use getAttribute("attributeName");

Solution 3:

You can't get away with adding custom attributes to HTML elements whilst still being valid. It will generally work in current browsers, but it's a bit fragile in that if you happen to pick a name that is in use (now or in the future) as an HTML or JavaScript property by any browser, the clash will stop it from working.

HTML5 proposes attributes whose names start with “data-​” as valid extension mechanisms. You could also consider namespaced elements in XHTML; this still isn't technically “valid XHTML” by the DTD but at least it is safe from collisions.

<a href="..." class="showItLink" textToShow="This is the text to show">HI

I suggest using the ‘title’ attribute for this particular purpose.

Solution 4:

The best way to do this kind of thing is to hide the text in another element and then toggle that element. Try something like this:

<!DOCTYPE htmlPUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"xml:lang="en"lang="en"><head><title>clear test</title><scripttype="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js"></script><scripttype="text/javascript">
            $(document).ready(function() {
                $("#show-it").click(function() {
                    $("#message").toggle();
                });
            });
        </script></head><body><div><aid="show-it"href="javascript:void(0);">show it</a><divid="message"style="display:none;"> hidden message</div>
            hello world
        </div></body></html>

Solution 5:

If your textToShow attribute was an expando property, then this.textToShow would not return undefined, but since it is a custom attribute, you need to use jQuery's this.attr("textToShow") or the standard DOM this.getAttribute("textToShow").

Post a Comment for "Html/javascript: Add Attribute To An Html Control"