YUI替换jQuery.replaceWith和jquery.append

时间:2009-11-04 08:29:12

标签: javascript jquery yui

我有一些jquery代码,我试图将其转换为YUI。我正在使用YUI 2.8。使用jquery我可以轻松地替换dom元素。是否有一种使用YUI代替jquery.replaceWith和jquery.append的好方法。我尝试编写我的函数如下,但这些只能采用文本,而我需要传递一个渲染的dom。 <p><a href="">what</a></p>(比这复杂得多。)

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
}

2 个答案:

答案 0 :(得分:1)

试试这个:

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
}

答案 1 :(得分:1)

这似乎对我有用:

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;
}