Functiondojo.attr

<script src="../../js/dojo.js"></script>
defined in dojo/_base/html.js

Handles normalized getting and setting of attributes on DOM Nodes. If 2 arguments are passed, and a the second argumnt is a string, acts as a getter.

If a third argument is passed, or if the second argumnt is a map of attributes, acts as a setter.

When passing functions as values, note that they will not be directly assigned to slots on the node, but rather the default behavior will be removed and the new behavior will be added using dojo.connect(), meaning that event handler properties will be normalized and that some caveats with regards to non-standard behaviors for onsubmit apply. Namely that you should cancel form submission using dojo.stopEvent() on the passed event object instead of returning a boolean value from the handler itself.

Usage

function (/*DomNode|String*/ node, /*String|Object*/ name, /*String?*/ value) (view source)
parametertypedescription
nodeDomNode|Stringid or reference to the element to get or set the attribute on
nameString|Objectthe name of the attribute to get or set.
valueStringOptional. The value to set for the attribute

Examples

Example 1

// get the current value of the "foo" attribute on a node
dojo.attr(dojo.byId("nodeId"), "foo");

// we can just pass the id:
dojo.attr("nodeId", "foo");

// use attr() to set the tab index
dojo.attr("nodeId", "tabindex", 3);

// set multiple values at once, including event handlers:
dojo.attr("formId", {
    "foo": "bar",
    "tabindex": -1,
    "method": "POST",
    "onsubmit": function(e){
        // stop submitting the form. Note that the IE behavior
        // of returning true or false will have no effect here
        // since our handler is connect()ed to the built-in
        // onsubmit behavior and so we need to use
        // dojo.stopEvent() to ensure that the submission
        // doesn't proceed.
        dojo.stopEvent(e);

        // submit the form with Ajax
        dojo.xhrPost({ form: "formId" });
    }
});