Jquery get element containing child element with specific html value

后端 未结 5 1916
执笔经年
执笔经年 2021-02-19 19:22

I would like to use Jquery to add a class to \"li\" element that contains a \"span\" element with a html/val equal to zero.

For Example if my code looks like this:

相关标签:
5条回答
  • 2021-02-19 19:41

    Here's a fast way to to it:

    $('li .num').each(function(){
        if ( $(this).text() == '0') $(this).parent().addClass('disabled');
    }); 
    

    With a jsFiddle example.

    0 讨论(0)
  • 2021-02-19 19:47

    This should do what you want.

    $('li').each(function(){
        if( $(this).find('span.num').text() == '0' ) $(this).addClass('disabled')
    });
    

    JS Fiddle

    I would have suggested the following:

    $('li').has('span.num:contains(0)').addClass('disabled')
    

    But it doesn't work, as it checks if the value exists inside the html — not for an exact match. In this case, each of the span.num elements have a 0 in them, so every li would get the selected class. There doesn't seem to be an :equals() counterpart to the :contains() selector.

    0 讨论(0)
  • 2021-02-19 19:53

    Try:

    $('li span.num').filter(
        function(i){
            return $(this).text() == '0';
        }).closest('li').addClass('selected');
    

    JS Fiddle demo.

    0 讨论(0)
  • 2021-02-19 19:53

    You can match the <span> element with filter(), then get its parent <div> with parent():

    $("li > span.num").filter(function() {
        return $(this).text() === "0";
    }).parent().addClass("disabled");
    
    0 讨论(0)
  • 2021-02-19 20:02

    Try this.

    $('ul span.num').filter(function(){
        return $(this).text() == "0";
    }).parent().addClass('disabled');
    

    Demo

    0 讨论(0)
提交回复
热议问题