adeel salim
adeel salim

Reputation: 21

How can I select some elements from div using jquery?

How can I set values of some elements for e.g I have 9 div and I want to access some of those div using jquery.

Here is my HTML code:

 <div>1</div>
 <div>2</div>
 <div>3</div>
 <div>4</div>
 <div>5</div>
 <div>6</div>
 <div>7</div>
 <div>8</div>

I want to loop through some part of div to give it a styling.

 var divs = $('div');

 for (var x= 3; x < divs.length; x++) {
         divs[x].css("color", "blue");
 }

But this gives me an error. Any ideas on how I can access it?

Thank you.

Upvotes: 1

Views: 76

Answers (5)

Archana Parmar
Archana Parmar

Reputation: 578

Please see my code. I'm adding Code Snippet. I clicked button "Style Div" to change color of alternate div's.

 function styleDiv()
    {
        var divLength = $(".MainDiv div");
        for (var i = 1; i < divLength.length; i+=2)
        {
            $(divLength[i]).css("color", "blue");
        }

    }
.styleButton
{
margin-bottom: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="styleButton">
    <input onclick="styleDiv()" type="button" value="Style Div" />
</div>

<div class="MainDiv">
    <div>1 div</div>
    <div>2 div</div>
    <div>3 div</div>
    <div>4 div</div>
    <div>5 div</div>
    <div>6 div</div>
    <div>7 div</div>
    <div>8 div</div>
</div>

I hope this helps :-)

Thanks

Upvotes: 2

Nir Tzezana
Nir Tzezana

Reputation: 2342

Try this:

var count = 0;
$("div").each(function(){
    if (count>3) {
        $(this).css("color","red");
    }
    count++;
});

Upvotes: 0

Shadow Fiend
Shadow Fiend

Reputation: 1829

here is a solution without jquery.

var divs = document.getElementsByTagName('DIV');
var r = 5;
var g = 10;
var b = 15;
for (var i = 0; i < divs.length; i++) {
  divs[i].style.backgroundColor = "rgb(" + r + "," + g + "," + b +")";
  r += 30;
  g += 50;
  b += 70;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>

I know your tag says jquery but I would like to show to you that you can use pure javascript.

Upvotes: 0

waranlogesh
waranlogesh

Reputation: 994

 var divs = $('div');
    for(var x= 3; x < divs.length; x++){
         $(divs[x]).css("color", "blue");
     }

In your example divs[x] was not an jquery object so it raised error. Convert it to jquery object $(divs[x]).

Upvotes: 0

guradio
guradio

Reputation: 15555

  1. Use :lt()

Description: Select all elements at an index less than index within the matched set.

$('div:lt(3)').css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>

Upvotes: 1

Related Questions