Jquery apuntando a un elemento

Assume the following situation

<div>
 <div1>

   <divA>
   </divA>

  <divB>
  </divB>

 </div1>

 <div2>
 </div2>

</div>

I would like to target <div1>, hacer una addClass() on it without adding a class to its child.

Traté de usar :nth-child(1) selector, o :eq() (I am using Jquery) . But the :nth-child(1) adds the class to all the 1-children element and :eq() doesn't fit because I want toi target <div1> from its parent element.

¿Alguien podría ayudar?

Mejor, Newben

preguntado el 30 de junio de 12 a las 16:06

3 Respuestas

A truely cross browser version too:

$('div').children('div1').addClass('la');

And if these divs don't have classes:

$('div').children().each(function(){
    $(this).addClass('la');
    break;
});

Respondido el 30 de junio de 12 a las 17:06

I don't think he really has a tag called <div1>, I think that's just for illustration of which <div> he wants to add the class to. - mVChr

@mVChr vague questions r us, he should of made clear whether or not these divs had classes, Ok I'll amend - sammaye

Solo da un id or class to main parent div and first level of child div.

por ejemplo:

HTML

<div id="main">
 <div class="div1">

   <divA>
   </divA>

  <divB>
  </divB>

 </div>

 <div class="div2">
 </div>

</div>

jQuery

$('#main .div1').addClass('something');

Muestra de trabajo

O

$('#main div:eq(0)').addClass('something');

Muestra de trabajo

Respondido el 30 de junio de 12 a las 17:06

Doesn't seems to work : $('#main div:nth-child(1)').addClass("myclass"); works but adds classes to divA - épsilones

Assuming you can't edit the markup otherwise, you could run an each() on the elements and only apply the class the first time:

​$('div :nth-child(1)').each(function(i, el){
    if (i == 0) $(this).addClass('red-border');​​​​​​​​​​​​​​​​​​​​
});

Ver demo

Respondido el 30 de junio de 12 a las 17:06

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.