Skip to content

Commit

Permalink
Merge pull request #7 from piotr-gawron/create-from-dom-object
Browse files Browse the repository at this point in the history
Create from dom object
  • Loading branch information
JostCrow committed Jul 17, 2017
2 parents dd8d78e + 22aba6c commit 34a219b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/dual-listbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,15 @@ const SELECTED_MODIFIER = 'dual-listbox__item--selected';
class DualListbox {
constructor(selector, options={}) {
this.setDefaults();
this.select = document.querySelector(selector);

this.selected = [];
this.available = [];

if (this.isDomElement(selector)) {
this.select = selector;
} else {
this.select = document.querySelector(selector);
}

this._initOptions(options);
this._initReusableElements();
this._splitSelectOptions(this.select);
Expand Down Expand Up @@ -439,6 +443,17 @@ class DualListbox {
}
}
}

/**
* @Private
* Returns true if argument is a DOM element
*/
isDomElement(o) {
return (
typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"
);
}
}

export default DualListbox;
Expand Down
9 changes: 9 additions & 0 deletions test/dual-listbox.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -289,4 +289,13 @@ describe('Duallistbox', function() {
expect(dlb.available.length).toBe(10);
expect(dlb.selected.length).toBe(0);
});

it('should be able to create object from DOM element', () => {
let domParent = document.createElement("div");
domParent.innerHTML = FIXTURE_FILLED_SELECT;
let dlb = new DualListbox(domParent.getElementsByTagName('select')[0]);

expect(dlb.available.length).toBe(10);
expect(dlb.selected.length).toBe(0);
});
});

0 comments on commit 34a219b

Please sign in to comment.