简体   繁体   English

你如何使用jQuery通过它的html查找元素?

[英]How do you use jQuery to find an element by its html?

I am trying to find a way to use jQuery to get the first empty div with a certain class. 我试图找到一种方法来使用jQuery获取具有某个类的第一个空div。 I tried this: 我试过这个:

$(".box[html='']").

but it didn't work. 但它不起作用。 Is there an easy way to do this? 是否有捷径可寻?

That syntax only works for attributes. 该语法仅适用于属性。 For HTML contents, you can use .filter() : 对于HTML内容,您可以使用.filter()

$('.box').filter(function () {
    return $.trim($(this).html()) === '';
}).eq(0);

Edit : The problem with :empty is that line-breaks and spaces are not empty. 编辑 :问题:empty是换行符和空格不为空。 So: 所以:

<div> </div>
<div>
</div>

... won't match. ......不会匹配。

This should work: 这应该工作:

$('.box:empty:first')  

http://api.jquery.com/empty-selector/ http://api.jquery.com/empty-selector/

How about this: 这个怎么样:

You html: 你的HTML:

<div class="empty"></div>
<div class="empty"></div>

your script: 你的脚本:

$(document).ready(function(){
    $(".empty:empty:first").html("JJJJ");

});

Check this 检查一下

http://jsfiddle.net/y4Ef2/ http://jsfiddle.net/y4Ef2/

var boxEq;
$('div.box').each(function(i,obj){
  if (boxEq === void(0)) {
    if ($(obj).html() === '') {
      boxEq = i;
      break;
    }
  }
});

// this is your div
$('div.box').eq(boxEq);

Try this one: 试试这个:

$('.box').each(function(){
    if($(this).text().length == 0)
    //box is empty
});
$("div.box:empty").eq(0)

添加.eq(0)因为你说空了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM