2012-05-05 66 views
0

如果我有相似的元素的列表,使得:包裹件具有相同属性

<outer-container> 
    <element attribute="x" /> 
    <element attribute="x" /> 
    . 
    . 
    . 
    <element attribute="y" /> 
    <element attribute="z" /> 
</outer-container> 

我如何包装自己的集装箱内的attribute="x"这样的元素他们是谁?

<outer-container> 
    <inner-container> 
     <element attribute="x" /> 
     <element attribute="x" /> 
    </inner-container> 
    . 
    . 
    . 
</outer-container> 
+0

你能否澄清一点你正在尝试做什么?这很混乱。 – JakeParis

回答

1

我改变你的HTML,使其更容易测试。

<div> 
    <input attribute="x" /> 
    <input attribute="x" /> 
    <p>divider</p> 
    <input attribute="y" /> 
    <input attribute="z" /> 
</div> 

假设你希望所有的那种在一个容器中的元素,定位在第一个被发现的,你可以做到这一点。

// invoked like this 
wrapAll('input[attribute=x]', 'span'); 

// implemented like this 
function wrapAll(selector, wrapper) { 
    if (typeof wrapper === 'string') 
     wrapper = document.createElement(wrapper); 
    else if (!wrapper || !wrapper.nodeType) 
     throw "Illegal 'wrapper' argument." 

    var els = document.querySelectorAll(selector); 

    els[0].parentNode.insertBefore(wrapper, els[0]); 

    for(var i = 0, len = els.length; i < len; i++) 
     wrapper.appendChild(els[i]); 
} 

http://jsfiddle.net/5z2uA/4/


如果你想不同的连续组被包裹起来,你可以做到这一点。

// invoked like this 
wrapAdjacent('input[attribute=x]', 'span'); 

// implemented like this 
function wrapAdjacent(selector, wrapper) { 
    if (typeof wrapper === 'string') 
     wrapper = document.createElement(wrapper); 
    else if (!wrapper || !wrapper.nodeType) 
     throw "Illegal 'wrapper' argument." 

    var els = document.querySelectorAll(selector); 

    for (var i = 0, len = els.length; i < len;) { 
     var this_wrapper = wrapper.cloneNode(false); 
     els[i].parentNode.insertBefore(this_wrapper, els[i]); 
     do { 
      this_wrapper.appendChild(els[i]); 
      i++; 
     } 
     while (nextEl(this_wrapper) === els[i])  
    } 
} 
function nextEl(el) { 
    while (el && (el = el.nextSibling) && el.nodeType !== 1) {} 
    return el; 
} 

http://jsfiddle.net/5z2uA/5/

+0

一个很好的提醒,为什么我使用jQuery。 – iambriansreed

相关问题