【问题标题】:javascript replace div tags for p tags where it has no class [duplicate]javascript替换没有类的p标签的div标签[重复]
【发布时间】:2012-10-04 15:30:06
【问题描述】:

我想将 div 标签替换为 p 标签,但前提是 div 标签没有类。

所以这个:

<div class="myDiv">
   <div>sdfglkhj sdfgkhl sdfkhgl sdf</div>
   <div>dsf osdfghjksdfg hsdfg</div>
</div>

会变成:

<div class="myDiv">
   <p>sdfglkhj sdfgkhl sdfkhgl sdf</p>
   <p>dsf osdfghjksdfg hsdfg</p>
</div>

我试过.replace("&lt;div&gt;", "&lt;p&gt;").replace("&lt;/div&gt;","&lt;/p&gt;"),但这会将结束标记替换为一个类。

【问题讨论】:

  • 不替换标签为什么不在css中添加一个类并指定你想要的规则?
  • 这可能会有所帮助:stackoverflow.com/questions/8584098/…
  • 好吧,你需要先检查类是否存在。你有 jQuery 还是只有纯 javascript?

标签: javascript replace


【解决方案1】:

这可以通过 jQuery 使用 :not() 选择器和 .unwrap() .wrap() 轻松完成

$('div:not([class])').contents().unwrap().wrap('<p/>');

http://jsfiddle.net/matthewbj/ujLHk/

【讨论】:

  • 您是否尝试过它是否适用于这样的情况:
    有效?
【解决方案2】:
$(document).ready(function () {

  $('div').each(function () {
    var html = this.innerHTML;
    if (! $(this).attr('class')) {
       $(this).replaceWith('<p>' + html + '</p>');
    }
  });
});

【讨论】:

  • 这不起作用。 TypeError: $(this).replace is not a function
  • 对不起,我错过了,是replaceWith,现在正在编辑...
【解决方案3】:

这可能会帮助您使用 jQuery 选择器来获取没有类的 div:

jQuery get all divs which do not have class attribute

【讨论】:

    【解决方案4】:
    $(document).ready(function()
    {
        $('.myDiv div').contents().unwrap().wrap('<p/>');
    });
    

    $(document).ready(function()
    {
        $('.myDiv div').each(function()
        {
            $(this).replaceWith($('<p>' + $(this).html() + '</p>'))
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多