How to convert a JavaScript object to a YUI 3 node?

1.6k views Asked by At

In my HTML I have something like this

<input type="button" value="Delete" onclick="delete(this);"/>

and in the JavaScript file I define my function "delete" like this:

YUI().use('node', functioin(Y) {
   function delete(el){
       //Here is the problem
       el.get('parentNode');
   }
}

The problem is, I want to convert the "el" object (which is a normal JavaScript object) to a node of YUI 3 so that I can use YUI 3's functions more conveniently. And I don't know how to do it.

What is the solution?

1

There are 1 answers

0
Eric Ferraiuolo On BEST ANSWER

YUI 3’s Y.Node constructor can simply take in a DOM element or selector string and return a new Y.Node instance:

// returns a Y.Node instance wrapping a div DOM element
var node = new Y.Node(document.createElement('div'));

But, the preferred way is the use the convenient Y.one factory method:

// returns a Y.Node instance wrapping a div DOM element
var node = Y.one(document.createElement('div'));

Also, YUI 3 has a Y.NodeList class which represents a collection of Y.Node instances:

// returns a Y.NodeList representing all divs on the page
var divs = new Y.NodeList(document.getElementsByTagName('div'));

// or using the convenient Y.all NodeList factory method:
divs = Y.all(document.getElementsByTagName('div'));

// …and finally the preferred way to do this using a selector string:
divs = Y.all('div');

In generally, use Y.one and Y.all to rerun a Y.Node and Y.NodeList instance respectively; this is how you will see YUI 3 code written, and what all the examples will use.

For your specific use case of wanting to remove a DOM element which you already hold a reference to you could do the following using YUI 3’s Y.Node class:

// assumes el is a DOM element reference
Y.one(el).remove();