Reputation: 997
I don't understand why this doesn't work:
$('article').addClass('new-article');
$($('.new-article').find('div')[1]).addClass('new-row');
.row {
color: red;
}
.new-row {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article>
<div class="row">text text 1</div>
<div class="row">text text 2</div>
<div class="row">text text 3</div>
<div class="row">text text 4</div>
<div class="row">text text 5</div>
<div class="row">text text 6</div>
<div class="row">text text 7</div>
<div class="row">text text 8</div>
</article>
What I want to achieve is that to add that custom class on second div and apply custom css, and also to add this on fourth div as well. I only need it on second and fourth div.
I know that I didn't add in jsfiddle part of the code for that fourth div, but logic should be the same...
Any ideas?
EDIT : I changed that custom to new and updated link, sorry about this.
Problem is that I only want to have blue text in second div and fourth div and not in all divs.
Upvotes: 2
Views: 65
Reputation: 1779
First of all, be sure that the DOM is actually ready when fetching by index.
Secoundary the use of .eq()
gets everything easier, so:
$( document ).ready(function() {
$( "div:eq(1)" ).addClass( "new-row" );
$( "div:eq(3)" ).addClass( "new-row" );
});
put the script in the <head>
of the document.
http://jsfiddle.net/mh4b741w/9/
Upvotes: 0
Reputation: 67505
Use jquery function filter
to target just 2nd and 4th div
s :
$('article').addClass('new-article');
$('.new-article div').filter(function( index ){
return index == 1 || index == 3;
}).addClass('new-row');
Hope this helps.
$('article').addClass('new-article');
$('.new-article div').filter(function( index ){
return index == 1 || index == 3;
}).addClass('new-row');
.row{
color:red;
}
.new-row{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article>
<div class="row">text text 1</div>
<div class="row">text text 2</div>
<div class="row">text text 3</div>
<div class="row">text text 4</div>
<div class="row">text text 5</div>
<div class="row">text text 6</div>
<div class="row">text text 7</div>
<div class="row">text text 8</div>
</article>
Upvotes: 2