Skip to content

select()

Karl edited this page Nov 4, 2017 · 18 revisions

Selects an item.

The method accepts a single argument in the following forms:

  • HTMLElement - the selectable element you want to select.
  • Number - the index of the selectable element (not it's index in the parentNode).
  • Object - a reference to the item stored in the items array.
  • Array - an array of nodes, indexes or objects. You may also pass instances of HTMLCollection or NodeList.

Examples

<ul>
    <li class="ul-selectable"><li>
    <li class="ul-selectable"><li>
    <li class="ul-selectable"><li>
    <li class="ul-selectable"><li>
    ...
</ul>

Select the second item

// as a node
var item = document.querySelectorAll("li")[1];
selectable.select(item);

// as an index
selectable.select(1);

// as a reference to the item
var item = selectable.items[1];
selectable.select(item);

Selecting multiple items

// Select the first 3 items via their indexes
var items = [0,1,2];
selectable.select(items);

// select all items with className "my-class"
var items = document.getElementsByClassName("my-class");
selectable.select(items);

// select all list items
var items = document.querySelectorAll("li");
selectable.select(items);

Using indexes

If selecting an item via an index, you must pass the index as the node would appear in the collection of selectable items, not the node's position relative to it's sibling elements.

<ul>
    <li class="ul-selectable"><li> // index 0
    <li><li>
    <li><li>
    <li class="ul-selectable"><li> // index 1
    <li class="ul-selectable"><li> // index 2
    <li class="ul-selectable"><li> // index 3
    <li><li>
    <li class="ul-selectable"><li> // index 4
</ul>

Select the first and second items

// incorrect
selectable.select([0,3]);

// correct
selectable.select([0,1]);
Clone this wiki locally