jQuery: Select only a class containing a string?

前端 未结 1 1140
暖寄归人
暖寄归人 2020-12-09 08:59

I\'m currently using this to get the class for a specific bit of HTML on the page:

$(this).parent(\"div\").attr(\'class\')

But that d

相关标签:
1条回答
  • 2020-12-09 09:42

    Select divs that have the status_billed class:

    $(this).parent('div.status_billed')
    

    Select divs whose class attribute contains status_:

    $(this).parent('div[class*=status_]')
    

    That's about the best you'll get with jQuery selectors. You can do better using .filter():

    $(this).parent('div').filter(function ()
    {
        var classes = $(this).attr('class').split(' ');
        for (var i=0; i<classes.length; i++)
        {
            if (classes[i].slice(0,7) === 'status_')
            {
                return true;
            }
        }
        return false;
    });
    

    ...but I'm not sure why you're doing all this - .parent() returns at most 1 element. Did you mean .closest() or .parents()?

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