Native: Window

Следующие ниже функции рассматриваются как методы Window.

Функция: $

У функции dollar двойная цель: Получить элемент по его идентификатору ID, а также «захватить» все методы Element элемента в Internet Explorer.

Синтаксис:

var myElement = $(el);

Аргументы:

  1. el - Элемент для расширения. Может быть следующих типов:
    • (element) Элемент будет расширен, если этого еще не происходило.
    • (string) Строка, содержащая требуемый идентификатор DOM элемента.
    • (object) Если объект содержит метод toElement, то toElement будет вызван чтобы возвратить требуемый элемент.

Возвращает:

  • (element) Элемент DOM.
  • (null) Возвращает null, если не было совпадений с указанным идентификатором, или если метод toElement не возвратил элемент.

Примеры:

Получение элемента DOM по идентификатору:

var myElement = $('myElement');

Получение элемента DOM по ссылке:

var div = document.getElementById('myElement');
div = $(div); //Элемент со всеми применяемыми к нему медотами Element.

Заметки:

  • Этот метод полезен, когда непонятно, ведется ли работа непосредственно с элементами или же с их идентификаторами. Так же он гораздо удобней для записи, чем document.getElementById().
  • В Internet Explorer Element расширяется при первом вызове функцти $ на него, и все методы Element становятся доступными.
  • Браузеры, поддерживающие HTMLElement, такие как Safari, Firefox, и Opera, автоматически применяют все методы Element для каждого элемента DOM.
  • Поскольку MooTools обнаруживает, должен ли быть расширен элемент или нет, то эта функция может быть вызвана на этот элемент несколько раз без каких-либо негативных последствий.

Функция: $$

Выбирает и расширяет элементы DOM. Элементы массивов, возвращенных с помощью функции $$, будут также содержать все применяемые к ним методы Element.

Синтаксис:

var myElements = $$(aTag[, anElement[, Elements[, ...]);

Аргументы:

  • Следующие аргументы могут приниматься в любом количестве:
    • узлы HTMLCollections,
    • массивы элементов,
    • элементы, или
    • строки в виде селекторов.

Возвращает:

  • (array) - Массив совпавщих с аргументами элементов DOM, разширенных с помощью функции $.

Примеры:

Получение элементов по именам их тегов:

$$('a'); //Возвращает все элементы с тегом <a>.
$$('a', 'b'); //Возвращает все элементы с тегами <a> и <b>.

Применение CSS селекторов, когда Selectors включен:

$$('#myElement'); //Возвращает  массив, содержащий только элемент с идентификатором 'myElement'.
$$('#myElement a.myClass'); //Возвращает массив всех элементов с тегом <a> и с классом 'myClass' в пределах элемента DOM с идентификатором 'myElement'.

Более сложное применение функции $$:

//Создает массив всех элементов и селекторов, принятых в качестве аргументов.
$$(myelement1, myelement2, 'a', '#myid, #myid2, #myid3', document.getElementsByTagName('div'));

Заметки:

  • Когда Selectors загружен, функция $$ будет также принимать CSS селекторы. В противном случае только селекторы, описывающие имена тегов.
  • Если выращение не обнаружит ниодного элемента, то будет возвращен пустой массив.
  • Тип возвращенных с помощью фонкции $$ методов элемента всегда будет массивом (array), независимо от количества результатов.

Смотрите также:

  • Обтаритесь в раздел Selectors за документацией по использованию селекторов, как и где их можно применять в рамках этого фреймворка.

Native: Element

Custom Native to allow all of its methods to be used with any extended DOM Element.

Element Method: constructor

Creates a new Element of the type passed in.

Синтаксис:

var myEl = new Element(element[, properties]);

Аргументы:

  1. element - (mixed) The tag name for the Element to be created or an actual DOM element.
  2. properties - (object, optional) Calls the Single Argument version of Element:set with the properties object passed in.

Возвращает:

  • (element) A new MooTools extended HTML Element.

Примеры:

var myAnchor = new Element('a', {

    'href': 'http://mootools.net',
    'class': 'myClass',
    'html': 'Click me!',
    'styles': {

        'display': 'block',
        'border': '1px solid black'
    },
    'events': {
        'click': function(){

            alert('clicked');
        },
        'mouseover': function(){
            alert('mouseovered');
        }

    }
});

Смотрите также:

Element Method: getElement

Gets the first descendant element whose tag name matches the tag provided. If Selectors is included, CSS selectors may also be passed.

Синтаксис:

var myElement = myElement.getElement(tag);

Аргументы:

  1. tag - (string) Tag name of the element to find.

Возвращает:

  • (mixed) If a match is found, the Element will be returned. Otherwise, returns null.

Примеры:

var firstDiv = $(document.body).getElement('div');

Заметки:

  • This method is also available for Document instances.
  • This method gets replaced when Selectors is included.
  • Selectors enhances Element:getElement so that it matches based on CSS selectors.

Смотрите также:

  • See Selectors for documentation on selectors for use anywhere they are accepted throughout the framework.

Element Method: getElements

Collects all decedent elements whose tag name matches the tag provided. If Selectors is included, CSS selectors may also be passed.

Синтаксис:

var myElements = myElement.getElements(tag);

Аргументы:

  1. tag - (string) String of the tag to match.

Возвращает:

  • (array) An Elements array of all matched Elements.

Примеры:

var allAnchors = $(document.body).getElements('a');

Заметки:

  • This method is also available for Document instances.
  • This method gets replaced when Selectors is included.
  • Selectors enhances Element:getElements so that it matches based on CSS selectors.

Смотрите также:

  • See Selectors for documentation on selectors for use anywhere they are accepted throughout the framework.

Element Method: getElementById

Gets the element with the specified id found inside the current Element.

Синтаксис:

var myElement = anElement.getElementById(id);

Аргументы:

  1. id - (string) The ID of the Element to find.

Возвращает:

  • (mixed) If a match is found, returns that Element. Otherwise, returns null.

Примеры:

var myChild = $('myParent').getElementById('myChild');

Заметки:

  • This method is not provided for Document instances as document.getElementById is provided natively.

Element Method: set

This is a "dynamic arguments" method. Properties passed in can be any of the 'set' properties in the Element.Properties Hash.

Синтаксис:

myElement.set(arguments);

Аргументы:

  • Two Arguments (property, value)
    1. property - (string) The string key from the Element.Properties Hash representing the property to set.
    2. value - (mixed) The value to set for the specified property.
  • One Argument (properties)
    1. properties - (object) Object with its keys/value pairs representing the properties and values to set for the Element (as described below).

Возвращает:

  • (element) This Element.

Примеры:

With Property and Value:

$('myElement').set('text', 'text goes here');
$('myElement').set('class', 'active');

//The 'styles' property passes the object to Element:setStyles.
var body = $(document.body).set('styles', {
    'font': '12px Arial',
    'color': 'blue'

});

With an Object:

var myElement = $('myElement').set({

    //The 'styles' property passes the object to Element:setStyles.
    'styles': {
        'font': '12px Arial',
        'color': 'blue',
        'border': '1px solid #f00'

    },
    //The 'events' property passes the object to Element:addEvents.
    'events': {
        'click': function(){ alert('click'); },
        'mouseover': function(){ this.addClass('over') }

    },
    //Any other property uses Element:setProperty.
    'id': 'documentBody'
});

Заметки:

  • All the property arguments are passed to the corresponding method of the Element.Properties Hash.
  • If no matching property is found in Element.Properties, it falls back to Element:setProperty.
  • Whenever using Element:setProperty to set an attribute, pass in the lowercase, simplified form of the property. For Пример:
    • use 'for', not 'htmlFor',
    • use 'class', not 'className'
    • use 'frameborder', not 'frameBorder'
    • etc.

Смотрите также:

Element Method: get

This is a "dynamic arguments" method. Properties passed in can be any of the 'get' properties in the Element.Properties Hash.

Синтаксис:

myElement.get(property);

Аргументы:

  1. property - (string) The string key from the Element.Properties Hash representing the property to get.

Возвращает:

  • (mixed) The result of calling the corresponding 'get' function in the Element.Properties Hash.

Примеры:

Using Custom Getters:

var tag = $('myDiv').get('tag'); //Returns "div".

Fallback to Element Attributes:

var id = $('myDiv').get('id'); //Returns "myDiv".

var value = $('myInput').get('value'); //Returns the myInput element's value.

Заметки:

Смотрите также:

Element Method: erase

This is a "dynamic arguments" method. Properties passed in can be any of the 'erase' properties in the Element.Properties Hash.

Синтаксис:

myElement.erase(property);

Аргументы:

  1. property - (string) The string key from the Element.Properties Hash representing the property to erase.

Возвращает:

  • (mixed) The result of calling the corresponding 'erase' function in the Element.Properties Hash.

Примеры:

$('myDiv').erase('id'); //Removes the id from myDiv.

$('myDiv').erase('class'); //myDiv element no longer has any class names set.

Note:

Смотрите также:

Element Method: match

Tests this Element to see if it matches the argument passed in.

Синтаксис:

myElement.match(match);

Аргументы:

  1. match - can be a string or element
    • (string) The tag name to test against this element. If Selectors is included, any single CSS selectors may also be passed.
    • (element) An element to match; returns true if this is the actual element passed in.

Возвращает:

  • (boolean) If the element matched, returns true. Otherwise, returns false.

Примеры:

Using a Tag Name:

//Returns true if #myDiv is a div.
$('myDiv').match('div');

Using a CSS Selector:

//Returns true if #myDiv has the class foo and is named "bar"
$('myDiv').match('.foo[name=bar]');

Using an Element:

var el = $('myDiv');
$('myDiv').match(el); //Returns true

$('otherElement').match(el); //Returns false

Element Method: inject

Injects, or inserts, the Element at a particular place relative to the Element's children (specified by the second the argument).

Синтаксис:

myElement.inject(el[, where]);

Аргументы:

  1. el - (mixed) el can be the id of an element or an element.
  2. where - (string, optional: defaults to 'bottom') The place to inject this Element. Can be 'top', 'bottom', 'after', or 'before'.

Возвращает:

  • (element) This Element.

Примеры:

JavaScript
var myFirstElement  = new Element('div', {id: 'myFirstElement'});

var mySecondElement = new Element('div', {id: 'mySecondElement'});
var myThirdElement  = new Element('div', {id: 'myThirdElement'});

Resulting HTML
<div id="myFirstElement"></div>
<div id="mySecondElement"></div>
<div id="myThirdElement"></div>

Inject to the bottom:

JavaScript
myFirstElement.inject(mySecondElement);
Resulting HTML
<div id="mySecondElement">
    <div id="myFirstElement"></div>
</div>

Inject to the top:

JavaScript
myThirdElement.inject(mySecondElement, 'top');
Resulting HTML
<div id="mySecondElement">
    <div id="myThirdElement"></div>

    <div id="myFirstElement"></div>
</div>

Inject before:

JavaScript
myFirstElement.inject(mySecondElement, 'before');

Resulting HTML
<div id="myFirstElement"></div>
<div id="mySecondElement"></div>

Inject After:

JavaScript
myFirstElement.inject(mySecondElement, 'after');
Resulting HTML
<div id="mySecondElement"></div>

<div id="myFirstElement"></div>

Смотрите также:

Element:adopt, Element:grab, Element:wraps

Element Method: grab

Works as Element:inject, but in reverse.

Appends the Element at a particular place relative to the Element's children (specified by the where parameter).

Синтаксис:

myElement.grab(el[, where]);

Аргументы:

  1. el - (mixed) el can be the id of an element or an Element.
  2. where - (string, optional: default 'bottom') The place to append this Element. Can be 'top' or 'bottom'.

Возвращает:

  • (element) This Element.

Примеры:

JavaScript
var myFirstElement = new Element('div', {id: 'myFirstElement'});

var mySecondElement = new Element('div', {id: 'mySecondElement'});
 
myFirstElement.grab(mySecondElement);

Resulting HTML
<div id="myFirstElement">
    <div id="mySecondElement"></div>
</div>

Смотрите также:

Element:adopt, Element:inject, Element:wraps

Element Method: adopt

Works like Element:grab, but allows multiple elements to be adopted.

Inserts the passed element(s) inside the Element (which will then become the parent element).

Синтаксис:

myParent.adopt(el[, others]);

Аргументы:

  1. el - (mixed) The id of an element, an Element, or an array of elements.
  2. others - (mixed, optional) One or more additional Elements separated by a comma or as an array.

Возвращает:

  • (element) This Element.

Примеры:

JavaScript
var myFirstElement  = new Element('div', {id: 'myFirstElement'});

var mySecondElement = new Element('a', {id: 'mySecondElement'});
var myThirdElement  = new Element('ul', {id: 'myThirdElement'});

 
myParent.adopt(myFirstElement);
myParent2.adopt(myFirstElement, 'mySecondElement');
myParent3.adopt([myFirstElement, mySecondElement, myThirdElement]);

Resulting HTML
<div id="myParent">
    <div id="myFirstElement" />
</div>
<div id="myParent2">

    <div id="myFirstElement" />
    <a />
</div>
<div id="myParent3">
    <div id="myFirstElement" />

    <a />
    <ul />
</div>

Смотрите также:

Element:grab, Element:inject, Element:wraps

Element Method: wraps

Works like Element:grab, but instead of moving the grabbed element from its place, this method moves this Element around its target.

The Element is moved to the position of the passed element and becomes the parent.

Синтаксис:

myParent.wraps(el[, where]);

Аргументы:

  1. el - (mixed) The id of an element or an Element.
  2. where - (string, optional: default 'bottom') The place to insert the passed in element. Can be 'top' or 'bottom'.

Возвращает:

  • (element) This Element.

Примеры:

HTML
<div id="myFirstElement"></div>

JavaScript
var mySecondElement = new Element('div', {id: 'mySecondElement'});
mySecondElement.wraps($('myFirstElement'));

Resulting HTML
<div id="mySecondElement">
    <div id="myFirstElement"></div>
</div>

Element Method: appendText

Works like Element:grab, but instead of accepting an id or an element, it only accepts text. A text node will be created inside this Element, in either the top or bottom position.

Синтаксис:

myElement.appendText(text);

Аргументы:

  1. text - (string) The text to append.
  2. where - (string, optional: default 'bottom') The position to inject the text to.

Возвращает:

  • (element) The current Element instance.

Примеры:

HTML
<div id="myElement">Hey.</div>

JavaScript
$('myElement').appendText(' Howdy.');
Resulting HTML
<div id="myElement">Hey. Howdy.</div>

Element Method: dispose

Removes the Element from the DOM.

Синтаксис:

var removedElement = myElement.dispose();

Возвращает:

  • (element) This Element. Useful to always grab the return from this function, as the element could be injected back.

Примеры:

HTML
<div id="myElement"></div>

<div id="mySecondElement"></div>
JavaScript
$('myElement').dispose();

Resulting HTML
<div id="mySecondElement"></div>

Смотрите также:

Element Method: clone

Clones the Element and returns the cloned one.

Синтаксис:

var copy = myElement.clone([contents, keepid]);

Аргументы:

  1. contents - (boolean, optional: defaults to true) When set to false the Element's contents are not cloned.
  2. keepid - (boolean, optional: defaults to false) When true the cloned Element keeps the id attribute, if present. Same goes for any of the cloned childNodes.

Возвращает:

  • (element) The cloned Element.

Примеры:

HTML
<div id="myElement"></div>

JavaScript
//Clones the Element and appends the clone after the Element.
var clone = $('myElement').clone().injectAfter('myElement');

Resulting HTML
<div id="myElement">ciao</div>
<div>ciao</div>

Note:

  • The returned Element does not have attached events. To clone the events use Element:cloneEvents.
  • Values stored in Element.Storage are not cloned.
  • The clone element and its children are stripped of ids, unless otherwise specified by the keepid parameter.

Смотрите также:

Element Method: replaces

Replaces the Element with an Element passed.

Синтаксис:

var element = myElement.replaces(el);

Аргументы:

  1. el - (mixed) A string id representing the Element to be replaced with, or an Element reference.

Возвращает:

  • (element) This Element.

Примеры:

$('myNewElement').replaces($('myOldElement'));

//$('myOldElement') is gone, and $('myNewElement') is in its place.

Смотрите также:

Element Method: hasClass

Tests the Element to see if it has the passed in className.

Синтаксис:

var result = myElement.hasClass(className);

Аргументы:

  1. className - (string) The class name to test.

Возвращает:

  • (boolean) Returns true if the Element has the class, otherwise false.

Примеры:

HTML
<div id="myElement" class="testClass"></div>
JavaScript
$('myElement').hasClass('testClass'); //returns true

Element Method: addClass

Adds the passed in class to the Element, if the Element doesnt already have it.

Синтаксис:

myElement.addClass(className);

Аргументы:

  1. className - (string) The class name to add.

Возвращает:

  • (element) This Element.

Примеры:

HTML
<div id="myElement" class="testClass"></div>
JavaScript
$('myElement').addClass('newClass');
Resulting HTML
<div id="myElement" class="testClass newClass"></div>

Element Method: removeClass

Works like Element:addClass, but removes the class from the Element.

Синтаксис:

myElement.removeClass(className);

Аргументы:

  1. className - (string) The class name to remove.

Возвращает:

  • (element) This Element.

Примеры:

HTML
<div id="myElement" class="testClass newClass"></div>

JavaScript
$('myElement').removeClass('newClass');
Resulting HTML
<div id="myElement" class="testClass"></div>

Element Method: toggleClass

Adds or removes the passed in class name to the Element, depending on whether or not it's already present.

Синтаксис:

myElement.toggleClass(className);

Аргументы:

  1. className - (string) The class to add or remove.

Возвращает:

  • (element) This Element.

Примеры:

HTML
<div id="myElement" class="myClass"></div>

JavaScript
$('myElement').toggleClass('myClass');
Resulting HTML
<div id="myElement" class=""></div>
JavaScript
$('myElement').toggleClass('myClass');

Resulting HTML
<div id="myElement" class="myClass"></div>

Element Method: getPrevious

Returns the previousSibling of the Element (excluding text nodes).

Синтаксис:

var previousSibling = myElement.getPrevious([match]);

Аргументы:

  1. match - (string, optional): A tag name to match the the found element(s) with. If Selectors is included, a full CSS selector can be passed.

Возвращает:

  • (mixed) The previous sibling Element or null if none found.

Element Method: getAllPrevious

Like Element:getPrevious, but returns a collection of all the matched previousSiblings.

Element Method: getNext

As Element:getPrevious, but tries to find the nextSibling (excluding text nodes).

Синтаксис:

var nextSibling = myElement.getNext([match]);

Аргументы:

  1. match - (string, optional): A comma seperated list of tag names to match the found element(s) with. If Selectors is included, a full CSS selector can be passed.

Возвращает:

  • (mixed) The next sibling Element or null if none found.

Element Method: getAllNext

Like Element.getNext, but returns a collection of all the matched nextSiblings.

Element Method: getFirst

Works as Element:getPrevious, but tries to find the firstChild (excluding text nodes).

Синтаксис:

var firstElement = myElement.getFirst([match]);

Аргументы:

  1. match - (string, optional): A tag name to match the found element(s) with. if Selectors is included, a full CSS selector can be passed.

Возвращает:

  • (mixed) The first sibling Element or null if none found.

Element Method: getLast

Works as Element:getPrevious, but tries to find the lastChild.

Синтаксис:

var lastElement = myElement.getLast([match]);

Аргументы:

  1. match - (string, optional): A tag name to match the found element(s) with. if Selectors is included, a full CSS selector can be passed.

Возвращает:

  • (mixed) The first sibling Element, or returns null if none found.

Element Method: getParent

Works as Element:getPrevious, but tries to find the parentNode.

Синтаксис:

var parent = myElement.getParent([match]);

Аргументы:

  1. match - (string, optional): A tag name to match the found element(s) with. if Selectors is included, a full CSS selector can be passed.

Возвращает:

  • (mixed) The target Element's parent or null if no matching parent is found.

Element Method: getParents

Like Element:getParent, but returns a collection of all the matched parentNodes up the tree.

Element Method: getChildren

Returns all the Element's children (excluding text nodes). Returns as Elements.

Синтаксис:

var children = myElement.getChildren([match]);

Аргументы:

  1. match - (string, optional): A tag name to match the found element(s) with. if Selectors is included, a full CSS selector can be passed.

Возвращает:

  • (array) A Elements array with all of the Element's children, except the text nodes.

Element Method: hasChild

Checks all descendants of this Element for a match.

Синтаксис:

var result = myElement.hasChild(el);

Аргументы:

  1. el - (mixed) Can be an Element reference or string id.

Возвращает:

  • (boolean) Returns true if the passed in Element is a child of the Element, otherwise false.

Примеры:

HTML
<div id="Darth_Vader">

    <div id="Luke"></div>
</div>
JavaScript
if ($('Darth_Vader').hasChild('Luke')) alert('Luke, I am your father.'); // tan tan tannn...

Element Method: empty

Empties an Element of all its children.

Синтаксис:

myElement.empty();

Возвращает:

  • (element) This Element.

Примеры:

HTML
<div id="myElement">

    <p></p>
    <span></span>
</div>
JavaScript
$('myElement').empty();

Resulting HTML
<div id="myElement"></div>

Element Method: destroy

Empties an Element of all its children, removes and garbages the Element. Useful to clear memory before the pageUnload.

Синтаксис:

myElement.destroy();

Возвращает:

  • (null)

Element Method: toQueryString

Reads the child inputs of the Element and generates a query string based on their values.

Синтаксис:

var query = myElement.toQueryString();

Возвращает:

  • (string) A string representation of a all the input Elements' names and values.

Примеры:

HTML
<form id="myForm" action="submit.php">
    <input name="email" value="bob@bob.com" />

    <input name="zipCode" value="90210" />
</form>
JavaScript
$('myForm').toQueryString(); //Returns "email=bob@bob.com&zipCode=90210".

Element Method: getSelected

Returns the selected options of a select element.

Синтаксис:

var selected = mySelect.getSelected();

Возвращает:

  • (array) An array of the selected elements.

Примеры:

HTML
<select id="country-select" name="country">

    <option value="US">United States</option
    <option value ="IT">Italy</option>
</select>
JavaScript
$('country-select').getSelected(); //Returns whatever the user selected.

Note:

This method returns an array, regardless of the multiple attribute of the select element. If the select is single, it will return an array with only one item.

Element Method: getProperty

Returns a single element attribute.

Синтаксис:

var myProp = myElement.getProperty(property);

Аргументы:

  • property - (string) The property to be retrieved.

Возвращает:

  • (string) A string containing the Element's requested property.

Примеры:

HTML
<img id="myImage" src="mootools.png" title="MooTools, the compact JavaScript framework" alt="" />

JavaScript
var imgProps = $('myImage').getProperty('src'); //Возвращает: 'mootools.png'.

Element Method: getProperties

Gets multiple element attributes.

Синтаксис:

var myProps = myElement.getProperties(properties);

Аргументы:

  • properties - (strings) Any number of properties to be retrieved.

Возвращает:

  • (object) An object containing all of the Element's requested properties.

Примеры:

HTML
<img id="myImage" src="mootools.png" title="MooTools, the compact JavaScript framework" alt="" />

JavaScript
var imgProps = $('myImage').getProperties('id', 'src', 'title', 'alt');

//Возвращает: { id: 'myImage', src: 'mootools.png', title: 'MooTools, the compact JavaScript framework', alt: '' }

Element Method: setProperty

Sets an attribute or special property for this Element.

Аргументы:

  1. property - (string) The property to assign the value passed in.
  2. value - (mixed) The value to assign to the property passed in.

Возвращает:

  • (element) - This Element.

Примеры:

HTML
<img id="myImage" />
JavaScript
$('myImage').setProperty('src', 'mootools.png');

Resulting HTML
<img id="myImage" src="mootools.png" />

Note

  • Whenever using Element:setProperty to set an attribute, pass in the lowercase, simplified form of the property. For Пример:
    • use 'for', not 'htmlFor',
    • use 'class', not 'className'
    • use 'frameborder', not 'frameBorder'
    • etc.

Element Method: setProperties

Sets numerous attributes for the Element.

Аргументы:

  1. properties - (object) An object with key/value pairs.

Возвращает:

  • (element) This Element.

Примеры:

HTML
<img id="myImage" />

JavaScript
$('myImage').setProperties({
    src: 'whatever.gif',
    alt: 'whatever dude'

});
Resulting HTML
<img id="myImage" src="whatever.gif" alt="whatever dude" />

Element Method: removeProperty

Removes an attribute from the Element.

Синтаксис:

myElement.removeProperty(property);

Аргументы:

  1. property - (string) The attribute to remove.

Возвращает:

  • (element) This Element.

Примеры:

HTML
<a id="myAnchor" href="#" onmousedown="alert('click');"></a>

JavaScript
//Eww... inline JavaScript is bad! Let's get rid of it.
$('myAnchor').removeProperty('onmousedown');

Resulting HTML
<a id="myAnchor" href="#"></a>

Element Method: removeProperties

Removes numerous attributes from the Element.

Синтаксис:

myElement.removeProperties(properties);

Аргументы:

  1. properties - (strings) The attributes to remove, separated by comma.

Возвращает:

  • (element) This Element.

Примеры:

HTML
<a id="myAnchor" href="#" title="hello world"></a>
JavaScript
$('myAnchor').removeProperties('id', 'href', 'title');
Resulting HTML
<a></a>

Element Method: store

Stores an item in the Elements Storage, linked to this Element.

Синтаксис:

myElement.store(key, value);

Аргументы:

  1. key - (string) The key you want to assign to the stored value.
  2. value - (mixed) Any value you want to store.

Возвращает:

  • (element) This Element.

Пример:

$('element').store('someProperty', someValue);

Element Method: retrieve

Retrieves a value from the Elements storage.

Синтаксис:

myElement.retrieve(key[, default]);

Аргументы:

  1. key - (string) The key you want to retrieve from the storage.
  2. default - (mixed, optional) Default value to store and return if no value is stored.

Возвращает:

  • (mixed) The value linked to the key.

Пример:

$('element').retrieve('someProperty'); // returns someValue (see example above)

Hash: Element.Properties

This Hash contains the functions that respond to the first argument passed in Element:get, Element:set and Element:erase.

Adding a Custom Element Property

Element.Properties.disabled = {
 
    get: function(){

        return this.disabled;
    }
 
    set: function(value){

        this.disabled = !!value;
        this.setAttribute('disabled', !!value);
    }
 

};

Using a Custom Element Property

//Gets the "disabled" property.
$(element).get('disabled');

//Sets the "disabled" property to true, along with the attribute.
$(element).set('disabled', true);

Note:

Automatically returns the element for setters.

Using an Object:

Additionally, you can access these custom getters and setters using an object as the parameter for the set method.

Пример:

//Using set:

$(divElement).set({html: '<p>Hello <em>People</em>!</p>', style: 'background:red'});

 
//For new Elements (works the same as set):
new Element('input', {type: 'checkbox', checked: true, disabled: true});

Element Property: html

Setter:

Sets the innerHTML of the Element.

Синтаксис:

myElement.set('html', [htmlString[, htmlString2[, htmlString3[, ..]]]);

Аргументы:

  1. Any number of string parameters with HTML.

Возвращает:

  • (element) This Element.

Examples:

HTML
<div id="myElement"></div>
JavaScript
$('myElement').set('html', '<div></div>', '<p></p>');

Resulting HTML
<div id="myElement">
    <div></div>
    <p></p>
</div>

Getter:

Returns the inner HTML of the Element.

Синтаксис:

myElement.get('html');

Возвращает:

  • (text) This Element's innerHTML.

Element Property: text

Setter:

Sets the inner text of the Element.

Синтаксис:

myElement.set('text', text);

Аргументы:

  1. text - (string) The new text content for the Element.

Возвращает:

  • (element) This Element.

Examples:

HTML
<div id="myElement"></div>
JavaScript
$('myElement').set('text', 'some text');

//The text of myElement is now 'some text'.
Resulting HTML
<div id="myElement">some text</div>

Getter:

Gets the inner text of the Element.

Синтаксис:

var myText = myElement.get('text');

Возвращает:

  • (string) The text of the Element.

Examples:

HTML
<div id="myElement">my text</div>

JavaScript
var myText = $('myElement').get('text'); //myText = 'my text'.

Element Property: tag

Getter:

Returns the tag name of the Element in lower case.

Синтаксис:

var myTag = myElement.get('tag');

Возвращает:

  • (string) The tag name in lower case.

Examples:

HTML
<img id="myImage" />
JavaScript
var myTag = $('myImage').get('tag'); // myTag = 'img'.

Native: IFrame

Custom Native to create and easily work with IFrames.

IFrame Method: constructor

Creates an IFrame HTML Element and extends its window and document with MooTools.

Синтаксис:

var myIFrame = new IFrame([el][, props]);

Аргументы:

  1. el - (mixed, optional) The id of the IFrame to be converted, or the actual IFrame element. If its not passed, a new IFrame will be created (default).
  2. props - (object, optional) The properties to be applied to the new IFrame. Same as Element:constructor props argument.

Возвращает:

  • (element) A new IFrame HTML Element.

Примеры:

var myIFrame = new IFrame({

 
    src: 'http://mootools.net/',
 
    styles: {
        width: 800,
        height: 600,
        border: '1px solid #ccc'

    },
 
    events: {
 
        mouseenter: function(){
            alert('Welcome aboard.');
        },

 
        mouseleave: function(){
            alert('Goodbye!');
        },
 

        load: function(){
            alert('The iframe has finished loading.');
        }
 
    }

 
});

Заметки:

  • If the IFrame is from the same domain as the "host", its document and window will be extended with MooTools functionalities, allowing you to fully use MooTools within it.
  • If the IFrame already exists and has a different name than id, the name will be made the same as the id.
  • If the IFrame is from a different domain, its window and document will not be extended with MooTools methods.

Native: Elements

The Elements class allows Element methods to work on an Elements array, as well as Array Methods.

Elements Method: constructor

Синтаксис:

var myElements = new Elements(elements[, options]);

Аргументы:

  1. elements - (mixed) An array of elements or an HTMLCollection Object.

Возвращает:

Примеры:

Set Every Paragraph's Color to Red:

$$('p').each(function(el){

    el.setStyle('color', 'red');
});
 
//Because $$('myselector') also accepts Element methods, the below
//example has the same effect as the one above.

$$('p').setStyle('color', 'red');

Create Elements From an Array:

var myElements = new Elements(['myElementID', $('myElement'), 'myElementID2', document.getElementById('myElementID3')]);

Заметки:

  • In MooTools, every DOM function which returns a collection of nodes (such as $$) returns the nodes as instances of Elements.
  • Because Elements is an Array, it accepts all the Array methods, while giving precedence to Element and Elements methods.
  • Every node of the Elements instance has all the Element methods.

Смотрите также:

Elements Method: filter

Filters a collection of elements by a given tag name. If Selectors is included, this method will be able to filter by any selector. It also works like Array:filter, by filtering collection of elements with a function.

Синтаксис:

var filteredElements = elements.filter(selector);

Аргументы:

  1. selector - (mixed) A single CSS selector.

Возвращает:

  • (array) A subset of this Elements instance.

Эта документация распостраняется на правах Attribution-NonCommercial-ShareAlike 3.0 License.
Оригинал документации на английском.
© Linux.ria.ua, 2008-2024