Example: Set and Get Properties

This example demonstrates how to retrieve and use a Node instance and access DOM properties.

Press the button to get or set the FORM's offsetWidth.

Setting up the HTML

<form id="demo" action="#">
    <label>How wide is this form?</label>
    <input name="width" size="2">
    <input type="submit" value="Show Me">
</form>

Getting a Node Instance

The Y.one method accepts a Selector or HTML element and returns a Node instance. Let's go ahead and set up some variables for the node's representing our HTML.

var form = Y.one('#demo'),
    input = Y.one('#demo input[name=width]'),
    button = Y.one('#demo input[type=submit]');

Accessing Node Properties

The properties of a node can be accessed via its set and get methods.

In most cases, simple type of properties (strings, numbers, booleans) pass directly to/from the underlying DOM node, however properties representing other DOM nodes return Node or NodeList instances.

The Get Method

We can use the get method to read the FORM element's offsetWidth, which includes the style width, padding, and border.

width = form.get('offsetWidth');

The Set Method

The set method allows us to update the value of the INPUT element with the value of the FORM's offsetWidth property.

input.set('value', width);

Setting the Offset Width

The offsetWidth property of an HTML element is read only, however YUI makes this writeable as well. This assures that the final offsetWidth matches the value that is set, regardless of borders, padding, or box model.

form.set('offsetWidth', value);

Listening for Node Events

We will update the value of the INPUT when the BUTTON is pressed. The FORM's default action can be suppressed using the incoming Event object's preventDefault() method.

button.on('click', function(e) {
    e.preventDefault();
};

Complete Example Source

<form id="demo" action="#">
    <label>Width:</label>
    <input name="width" size="2">
    <input type="submit" value="Run">
</form>

<script type="text/javascript">
YUI().use('node', function(Y) {
    var form = Y.one('#demo'),
        input = Y.one('#demo input[name=width]'),
        button = Y.one('#demo input[type=submit]');

    form.on('submit', function(e) {
       e.preventDefault(); // keep the form from submitting

       var value = input.get('value'),
            width = form.get('offsetWidth');

       if (value == '') {
           input.set('value', width);
       } else if (!isNaN(parseInt(value))) {
            form.set('offsetWidth', value);
       }
    });
});
</script>