Learn YUI3 – Create new Element/Node and Apply CSS

I am continue on learning YUI and posting it here for all to read as part of . This post is a part of YUI node under YUI tutorial series.

Creating new Element using YUI3:
The below example will create DIV, SPAN and P and present different different scenarios.

Here is small CSS code used in the example:
.redTxt {color:red;}

Here is small piece of code used in the following example:
<div id="container">


JavaScript part of YUI:

No other module is used except default node module.

Container Element used to add dynamically created Elements:

var containerDiv = Y.one('#container');

OnClick Event handler. It will log the id of the clicked element where it is tied.
function onClick(e) {
Y.log('New Div onClick Event Fired with id=' + e.target.get('id'));

Created Div element, set id, and innerHTML attributes and assign to document to make it part of DOM.

// YUI's on() method is not chainable. So, it can only come on last.
Y.Node.create('<div/>').set('id', 'newDiv').set('innerHTML', 'New Div created').appendTo(containerDiv).on('click', onClick);

Doing the same thing as above except I am trying to access the newly created element and assigning the onClick handler later.
// Doing the above step in two steps
Y.Node.create('<div/>').set('id', 'newDiv').set('innerHTML', 'New Div created').appendTo(containerDiv);
newDiv = Y.one('#newDiv');
newDiv.on('click', onClick);

Create new SPAN with text in it at the time of creation:
Y.Node.create('<span id="newspan"> New Span Content</span>').appendTo(containerDiv);

Add Css a little to newly created span. For adding class or for working with class refer previous article on YUI Node.
// setStyle() for jQuery css()
span = Y.one('#newspan').setStyle('color', 'green');

Can be do everything on newly created element and then add to container? Yes.

var p = Y.Node.create('<p id="newp">Newly created Paragraph.</p>').addClass('redTxt');
p.setStyle('font-weight', 'bold');

If you forgot to add newly created element to document (Container) then that cannot be accessed using id attribute etc. For that you need to use the returned object at the time of object creation. YUI's On method is not chainable so it must not be used on the last part without appendTo().

Setting multiple Styles to an Element:
Use setStyles() instead of setStyle() and provide information in notation.

e.target.setStyles({'color': '#999999', 'fontWeight':'bold'});