【问题标题】:remove text before and after an html tag [duplicate]删除html标签前后的文本[重复]
【发布时间】:2015-12-16 23:24:50
【问题描述】:

如何使用 jQuery 或纯 JavaScript 删除下面代码中 <nospc/> 标记前后的空格? (我意识到我可以简单地手动删除空格,但有时在不呈现的 HTML 中使用空格和换行符会很方便。)

<div>
    <img src="" /><nospc/>
    <img src="" />
</div>

在完美的世界中,&lt;nospc/&gt; 将删除其自身前后的所有空白,&lt;nospc&gt; ... &lt;/nospc&gt; 将删除标记对之间的所有空白。

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

尝试使用 .contents() , .each() Node.nextSibling , Node.previousSibling , Node.textContent , String.prototype.replace()RegExp /\s+/

$("div").contents().each(function(i, el) {
  if (el.nodeName === "#text" && el.nextSibling 
       && el.nextSibling.nodeName === "NOSPC" 
     || el.nodeName === "#text" && el.previousSibling 
       && el.previousSibling.nodeName === "NOSPC" 
     || el.nodeName === "NOSPC") {
         el.textContent = el.textContent.replace(/\s+/g, "")
  }
});

console.log($("div").contents())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>
    <img src="" /> <nospc> </nospc> 
    <img src="" />
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-26
    • 2012-12-29
    • 1970-01-01
    • 2014-01-28
    • 2011-09-04
    • 2011-10-30
    • 2013-04-28
    • 2016-04-16
    相关资源
    最近更新 更多