Kirk Ross
Kirk Ross

Reputation: 7153

Syntax for targeting class inside element with var in Id?

What is the correct syntax for targeting a class which is a child element of an element with an id that includes a variable.

Without the var it works:

$( "#parent_el .child-class" )

What's the correct syntax if you add a variable, like so?

$( "#parent_el_" + uniqueIdForParent .child-class )

Upvotes: 0

Views: 71

Answers (1)

Vucko
Vucko

Reputation: 20844

For your situation:

var id = "1";
$("#parent_" +id+ " .child").css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="parent_1"><p class="child">Foo</p></div>

Also, you can use .find():

var id = "1";
$("#parent_"+id).find('.child').css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent_1"><p class="child">Bar</p></div>

Upvotes: 1

Related Questions