views:

321

answers:

2

I have some jquery code which I am trying to translate to YUI. I am using YUI 2.8. Using jquery I could have easily replaced a dom element. Is there a good way to use YUI in place of jquery.replaceWith and jquery.append. I tried writing my functions as below, but these can only take text, while I need to pass a rendered dom like. <p><a href="">what</a></p> (much more complex than this.)

function replaceWith(el_id, text){
    //YUI doesn't seem to have a good replacement for $.replaceWith. Writing one to simulate it for my usages.
    node_to_replace = YAHOO.util.Dom.get(el_id);
    if(node_to_replace){
 new_node = document.createTextNode(text);
 YAHOO.util.Dom.insertAfter(new_node, node_to_replace);
 node_to_replace.innerHTML = ''
    }
    return node_to_replace
}

function append(el_id, text){
    //YUI doesn't seem to have a good replacement for $.append. Writing one to simulate it for my usages.
    node_to_replace = YAHOO.util.Dom.get(el_id);
    if(node_to_replace){
 new_node = document.createTextNode(text);
 YAHOO.util.Dom.insertAfter(new_node, node_to_replace);
    }
    return node_to_replace
}
+1  A: 

Try with this:

function replaceWith(el_id, text){
    var node_to_replace = YAHOO.util.Dom.get(el_id);
    if(node_to_replace){
        var new_node=document.createElement("div");
        new_node.innerHTML=text; //Parse the code inside a new element
        var beforeNode=node_to_replace;
        for(i=0;i<new_node.childNodes.length;i++){
           //Move generated children after the replaced node
           YAHOO.util.Dom.insertAfter(new_node.childNodes[i], beforeNode);
           beforeNode=new_node.childNodes[i];
        }
        node_to_replace.parentNode.removeChild(node_to_replace);//Remove the replaced element
    }
    return node_to_replace
}

function append(el_id, text){
    var node_to_replace = YAHOO.util.Dom.get(el_id);
    if(node_to_replace){
        var new_node=document.createElement("div");
        new_node.innerHTML=text; //Parse the code inside a new element
        for(i=0;i<new_node.childNodes.length;i++){
           //Move generated children inside the node
           node_to_replace.appendChild(new_node.childNodes[i]);
        }
    }
    return node_to_replace
}
mck89
+1  A: 

This seems to be working for me:

function replaceWith(id, innerHTML) {
 var oldNode = YAHOO.util.Dom.get(id);
 var newNode = document.createElement(oldNode.tagName);
 newNode.id = id;
 newNode.innerHTML = innerHTML;
 YAHOO.util.Dom.get(id).parentNode.replaceChild(newNode, oldNode);
 return YAHOO.util.Dom.get(id);
}

function append(id, appendedText) {
 var elem = YAHOO.util.Dom.get(id);
 elem.innerHTML += appendedText;
 return elem;
}
artlung