TeTe TeTe - 5 months ago 42
jQuery Question

find elements which id contains two substrings

I have an HTML table and I need to change the CSS style to all de

<td>
whose
"id"
contains the substring
"_A_189"
and the substring
"_B_V_852"
using jquery. The substrings could be in any position of the string.

I use this, but it doen't work:

$('id:contains("_A_189"):contains("_B_V_852")').css(style);

Answer

You can use square brackets to select by attribute:

$("[id*='_A_189'][id*='_B_V_852']").css(style);

And in case of this question it's even better to narrow it down to only td elements:

$("td[id*='_A_189'][id*='_B_V_852']").css(style);

"[id*='str']" means "find an element where attribute 'id' contains string 'str' anywhere".

More info at jQuery documentation: http://api.jquery.com/attribute-contains-selector/

EDIT: This selector is available in css, not only in jQuery, so if '_A_189' and '_B_V_852' parts are static, you should consider adding it to your stylesheet instead of using scripts. For instance:

table td[id*='_A_189'][id*='_B_V_852'] {
    /* your styles */
}
Comments