Question

I'm still getting to grips with javascript, and am having trouble working out the correct syntax to select a DOM element. Would appreciate any points.

The html:

<div class="container"> 
  <label class="check_box_label">
    <input type="checkbox" class="checkbox">
    Checkbox Label
  </label>
  <select class="select">...</select>
</div>

When the checkbox value changes, if it is checked I want to do something with the select field (I'm using coffeescript)

jQuery ->
  $(".checkbox).change ->
    if $(this).is(":checked")
      $this.xxxxx(".select")

I've studied the jquery api, and experimented with various DOM traversing operators, but must be overlooking something simple. What operator should replace xxxx in my example above? From the API description, I thought closest should work, but it doesn't.

Was it helpful?

Solution

If this group of elements is always encapsulated within that .container div element then this should work:

$(this).closest('div.conainer').find('.select')

This is using closest to traverse up the DOM hierarchy (parent elements) and then find to traverse back down (child elements).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top