我可以在其HTML中选择包含“”的元素吗?

时间:2015-03-26 10:08:03

标签: jquery

例如:

<div class="el"> &nbsp ;&nbsp ;&nbsp ;&nbsp ;HasNbsp</div>
<div class="el">NoNbsp</div>

我想选择“&amp; nbsp”这是HTML的“.el”,我试过了:

$("div.el").html().contains("&nbsp;")

但jquery中不允许这样做。

这甚至可能吗?以及如果是的话。感谢。

注意:我不需要删除“&amp; nbsp”。我真的需要“&amp; nbsp;”

3 个答案:

答案 0 :(得分:4)

试试这个:

$(function() {
  var regEx = /&nbsp;/gm;
  var elements = $("div p").filter(function(index, ele) {
     if(regEx.test($(ele).html())) {
       return true;
    }
  });
 // elements will contains DOM elements which has &nbsp;
});

<强> DEMO

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="result">
<p>&nbsp; This contains space</p>
<p>hi, this doesn't</p>
  </div>

<script type="text/javascript">
$(function() {
  var regEx = /&nbsp;/gm;
  var elements = $("div p").filter(function(index, ele) {
 if(regEx.test($(ele).html())) {
   console.log("matched");
   return true;
}
  });
  $(elements).each(function() {
$(this).css({background: "red"});
  })
});
</script>

</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

在选择器中使用\u00a0而不是&nbsp;

因此,您需要这样做:

$("div.el").html().contains("\u00a0")

这是一个带有更多示例代码的CodePen:

4

答案 2 :(得分:0)

您想要过滤您的查询:

$("div.el").filter(function(){
    return $(this).html().indexOf(" ") > -1;
});

这将返回函数评估的元素为&#34; true&#34;,因此只需让您的函数在包含&#34;&amp; nbsp&#34;。

的元素上返回true。
相关问题