0

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 )
Kirk Ross
  • 6,413
  • 13
  • 61
  • 104
  • `$( "#parent_el_" +uniqueIdForParent+ " .child-class")`? [JSFiddle](http://jsfiddle.net/tyhwsspj/) – Vucko Jan 09 '15 at 20:26

1 Answers1

1

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>
Vucko
  • 20,555
  • 10
  • 56
  • 107