Jaanus
Jaanus

Reputation: 17866

How to do basic DOM manipulation (clear content, append to content) with YUI?

I am doing a project with YUI where I attempt to do things I have previously been doing with jQuery. I am finding it difficult to do some basic operations, and namely:

  1. clear content of DOM element
  2. append to content of DOM element

In jQuery, I would do:

$(".someSelector").empty().append("<div>something</div>");

How to do the above in YUI? Seems like it defers to W3C DOM spec in many aspects, I am not very familiar with that spec. If there's any specific W3C or such material I should use, please give specific links.

Upvotes: 0

Views: 9066

Answers (2)

Ryan McIlmoyl
Ryan McIlmoyl

Reputation: 221

YUI does not seem to provide the same level of DOM manipulation that jQuery does (although I haven't played with YUI3 yet, so this may change).

innerHTML definitely works, and was faster once upon a time, although I think this is changing in some modern browsers. Appending content is easy enough via the standard methods:

element.appendChild(childElement);

Clearing is a little more involved. I have actually ended up extending the YUI DOM utility and added this as a method:

removeChildren : function(elem)
{
    var theElement = this.get(elem);
    var elemChildren = theElement.childNodes;
    var childCount = elemChildren.length;
    for (var i = childCount -1; i >= 0; i--)
    {
        theElement.removeChild(theElement.childNodes[i]);
    }
}

It's important to note than when looping through the child nodes, I start with the last element and work my way to the front. This is because whenever a node is removed, the size of the array changes. Also, if I remove the node at position [0], all the elements of the array move down a position (meaning the element that was at position [1] now becomes the element at position [0]). If I was to start at the front of the array, I would miss elements, and quickly exceed the array's boundary.

Upvotes: 3

Gero
Gero

Reputation: 1841

Here is the YUI documentation for Dom methods.
Yahoo! UI Library > dom > YAHOO.util.Dom
Or try

YAHOO.util.Dom.get("somediv").innerHTML("<div>something</div>");

Upvotes: 3

Related Questions