Reddy
Reddy

Reputation: 1385

Help needed on contains()

Here is the HTML code of a radio button

<input type="radio" class="grgrgrtgxxxxfeegrgbrg">

I am trying to check whether radio button's name is having xx.
Here is my jquery code i have written

if($(this).prop('class').contains('xxxx'))
                               {
                                 alert("Yup");
                               }

Please tell me the Syntax mistake in it.

Upvotes: 0

Views: 99

Answers (3)

abhijit
abhijit

Reputation: 1968

var className = $(this).attr('class');
int i = className.IndexOf("xx");"
if(i > -1)
{alert("has the xx class");}

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074038

contains isn't a method of strings in JavaScript. Since from your question you really do want substring matching in the middle of a class name, you can use indexOf:

if ($(this).prop('class').indexOf('xx') >= 0)
{
    alert("Yup");
}

Note that you don't need jQuery for this at all, just use the reflected property of the DOM element:

if (this.className.indexOf('xx') >= 0)
{
    alert("Yup");
}

className reflects the "class" attribute.

Upvotes: 1

mck89
mck89

Reputation: 19231

contains is a jQuery method that works with elements not with strings so you must use string methods:

if($(this).prop('class').indexOf("xx")>-1)
{
    alert("Yup");
}

But as someone else said you can use hasClass:

if($(this).hasClass("xx")) ...

Upvotes: 3

Related Questions