If element contains certain text

前端 未结 3 1597
猫巷女王i
猫巷女王i 2020-12-06 10:23
$(\'.test\').css(\'background\',\'red\');

Some text

How can I .addClass(\'test\') if #exa

相关标签:
3条回答
  • 2020-12-06 11:10

    try the following code

    $('#example:contains("text")').addClass('test');
    

    Have a look here for examples and explanations of the :contains selector

    0 讨论(0)
  • 2020-12-06 11:15

    You can use $("#example") to get a jQuery wrapper for the element, then use text() to get its text, and use String#indexOf, e.g.:

    var ex = $("#example");
    if (ex.text().indexOf("text") !== -1) {
        ex.addClass("test");
    }
    

    You can also use :contains("text") in the selector as F. Calderan shows, although note that when you use non-standard pseudo-selectors like that, jQuery can't use the underlying browser's built-in stuff for finding elements, so it can be slower. The above will allow jQuery to use document.getElementById. There are only a few situations where the speed really matters, though.

    0 讨论(0)
  • 2020-12-06 11:17

    just use :contains pseudoclass

    $('#example:contains("text")').addClass('test');
    

    this will add the class to #example if it contains 'text'

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