简体   繁体   中英

jQuery like structure - ES6 JS Chaining

This is my first post on StackOverflow, so at beginning I'm sorry for my not full fluent English ;) But I try explain with what I have problem.

Here is live example

http://codepen.io/anon/pen/JKGbdE

 class S { constructor(selectors) { let self = this; this.elements(selectors); } elements(selectors) { this.selectors = selectors; let result = document.querySelectorAll(this.selectors); if( result.length == 1 ) { result = result[0]; this.element = result; } else { this.elements = [].slice.call(result); } this.nodes = result; return this.nodes; } parent() { let self = this; if( !!this.element ) { this.nodes = this.element.parentNode; } else { this.elements.forEach = (item, key) => { self.elements[key] = item.parentNode; }; this.nodes = this.elements; } return this.nodes; } result(a) { return this.nodes; } } window.$ = (selectors) => { let el = new S(selectors); return el; }; console.log('first ex: ', $('#el') ) console.log('second ex: ', $('#el').parent() ) 
 <html> <body> <div id="el">test</div> </body> </html> 

If you open browser console you will see something like this:

[Log] first ex: –

S {selectors: "#el", element: <div id="el">, nodes: <div id="el">, …} 

[Log] second ex: –

<body>…</body>

The second example is OK. I just want to return a HTML node. In the first example it should return only <div id="el /> .

Any suggestions?

In first ex: you are returning new S(...) and in second ex: - this.nodes (DOM objects).

Unless you extend JS DOM manipulation, you cannot expect getting DOMObject as response with all subfunctions working - jQuery also cannot give you this possibility.

Try console.log(jQuery('.anything')) - it also returns an object that has DOM object as item (with index 0 to be exact).

You should change your code so it will always return S object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM