2

Is there a way to select a component with multiple children, point to one of them and apply css properties or some class?

Let's say I have this div:

<div class="parent"> <div>Child 1</div> <div>Child 2</div> <div>Child 3</div> </div> 

I would like to apply a css property to the second div.

I've tried this:

$('.parent')[0].children[1].css('display', 'block') 

But I am getting this error: Cannot read property 'children' of undefined

What I don't understant is that if I log $('.parent')[0].children[1] into the console I get the child div, so, I supposed that would be the way, but it seems that I am wrong.

Is there a way to do that?

1
  • 1
    remove [0] =)) Commented Nov 13, 2020 at 0:54

3 Answers 3

2

When you use an array index on a jQuery object, it returns a DOM element, not a jQuery object, so you can't use jQuery methods on it. Use .eq() to keep it as jQuery objects.

$('.parent').eq(0).children().eq(1).css('display', 'block');
.parent div { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="parent"> <div>Child 1</div> <div>Child 2</div> <div>Child 3</div> </div>

Sign up to request clarification or add additional context in comments.

Comments

2

You can use find method on parent to select all child div elements and then use eq method to select specific child by index.

You can also do that with selector such as $('.parent > div:eq(1)')

$('.parent').find('div').eq(1).css('color', 'red')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="parent"> <div>Child 1</div> <div>Child 2</div> <div>Child 3</div> </div>

Comments

1

This code should work.

$(".container div").css("background-color", "red");
.container { background-color: blue; height: 100%; width: 100%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div>1</div> <div>2</div> <div>3</div> </div>

Just give the second div an ID and instead of using div use #second-div-id.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.