jQuery:转换为单个标签

时间:2012-12-17 10:24:51

标签: jquery-selectors

我想将以下HTML转换为单个标记: 之前:

<div class="Parent1">
    <div class="Child1">
        <a href="#">Child1</a>
      </div>
      <div class="Child2">
        <a href="#">Child2</a>
      </div>    
    </div>
    <div class="Parent2">
      <div class="Child1">
        <a href="#">Child1</a>
      </div>
      <div class="Child2">
        <a href="#">Child2</a>
      </div>
    </div>

之后:

<div class="Parent1">
  <button>Child1</button>
  <button>Child2</button>
</div>
<div class="Parent2">
  <button>Child1</button>
  <button>Child2</button>
</div>

我尝试了包装/展开。但它不起作用。我希望这是通用的。

2 个答案:

答案 0 :(得分:0)

试试这个(demo):

$('div[class^="Parent"]').each(function(index, parent) {
  var html = [];
  $('a', parent).each(function(index, child) {
      html.push('<button>'+$(child).html()+'</button>');
  });
  $(parent).html(html.join(''));
});

它假设父div有一个模式,但这不是一些常见的类名。

答案 1 :(得分:0)

一种方法:

$("a").unwrap().wrap("<button>").parent().text(function () { 
    return $(this).text();
});

http://jsfiddle.net/Tomalak/Gct7H/

另一个同样精神的人:

$("a").unwrap().replaceWith(function () {
    return $("<button>", {text: $(this).text()});
});

PS:实际上你想要选择比$("a")更具体的东西。可能是$("#container a")$("a.someClass"),具体取决于您的加价。