Ángel Pérez
Ángel Pérez

Reputation: 11

Selectors with jquery

I'm trying something with royal slide. I want to change the ID according the image change. I tried some stuff like using translateX values but it's really difficult to me, because I don't have much experience with jQuery/JavaScript. So I thought of another idea when I saw this:

<div class="rsNav rsBullets">
   <div class="rsNavItem rsBullet rsNavSelected"><span></span></div>
   <div class="rsNavItem rsBullet"><span></span></div>
   <div class="rsNavItem rsBullet"><span></span></div>
</div>

I thought that the best option was to use the :nth-child selector like this:

function colorfondo(){
if($('.RsNav:nth-child(1)').hasClass("RsNavselected")) {
   console.log('works!');
}

but it didn't work.

EDIT Maybe i didnt explain it very well. I just want something like this:

if (the first child has the rsNavSelected) { do something.}
elseif the second child has the rsNavSelected) { do something.} elseif the third child has the rsNavSelected { do something.} 

RE-EDIT I made it work,thats my function function colorfondo(){

if($('.rsNav div:first-child').hasClass("rsNavSelected")) {
console.log('rojo!');
} 
else if($('.rsNav div:nth-child(2)').hasClass("rsNavSelected")) {
console.log('azul!');
} 
else if($('.rsNav div:nth-child(3)').hasClass("rsNavSelected")) {
console.log('gris!');
} 
}

Now i need that this function doesnt stop and stay always working,any suggestions?

Upvotes: 1

Views: 126

Answers (2)

Alex
Alex

Reputation: 11245

RsNavselected is not equal to rsNavselected and RsNav is not rsNav.

HTML attributes values are case-sensitive, but HTML tag names and attributes not.

Use :

if($('.rsNav:nth-child(1)').hasClass("rsNavSelected")) {
   console.log('works!');
} 

Also, if you want to get first-child use .children() and .first() methods:

if($('.rsNav').children().first().hasClass("rsNavSelected")) {
   console.log('works!');
} 

Upvotes: 4

Abhishek Kasera
Abhishek Kasera

Reputation: 240

You can also use like :

if($('.rsBullets').find(".rsNavselected").length > 0) {
    console.log('works!');
} 

Upvotes: 0

Related Questions