Reputation: 121
On change or on load, whenever a user selects a grid option, I am trying to add the class to pull-left or pull-right to the divs (block_left
, media_right
) that are sibling to the selector grandparent grid
. However I am not able to select the siblings.
Here is the HTML
<div data-name="grid">
<div class="label">
<label>Grid</label>
</div>
<div class="input">
<select>
<option value="left_right">Left / Right</option>
<option value="left_media">Content / Media</option>
<option value="media_right" selected="selected">Media / Content</option>
</select>
</div>
</div>
<div data-name=“block_left”></div>
<div data-name=“media”></div>
Here is the jQuery
function blockGrid() {
var gridSelect = $('[data-name=”grid”] select');
$(gridSelect).each(function( index ) {
console.log( index + ": " + $( this ).val() );
// On Load
if($(this).val() == “media_right” ) {
$(this).closest('[data-name="grid"]').find('[data-name="media"]').addClass('pull-xs-left');
$(this).closest('[data-name="grid"]').find('[data-name="block_left"]').addClass('pull-xs-right');
};
// On Change
$(this).change(function() {
console.log('Grid changed to ' + $(this).val());
if($(this).val() == “media_right” ) {
$(this).closest('[data-name="grid"]').find('[data-name="media"]').addClass('pull-xs-left');
$(this).closest('[data-name="grid"]').find('[data-name="block_left"]').addClass('pull-xs-right');
} else {
$(this).closest('[data-name="grid"]').find('[data-name="media"]').removeClass('pull-xs-left');
$(this).closest('[data-name="grid"]').find('[data-name="block_left"]').removeClass('pull-xs-right');
};
});
});
};
Upvotes: 0
Views: 1388
Reputation: 1074138
find
doesn't look for siblings, it looks for descendants. siblings
looks for siblings.
So
$(this).closest('[data-name="grid"]').siblings('[data-name="media"]').addClass('pull-xs-left');
// -----------------------------------^^^^^^^^
...and so on.
Alternately, wrap the entire structure in a common container, use closest
to go up to that container (e.g., one level above data-name="grid"
), and then use find
.
Side note: I suspect it's just an issue you introduced when asking the question, but the quotes on the siblings are wrong:
<div data-name=“block_left”></div>
<div data-name=“media”></div>
Those “
characters should be "
(or '
, or no quotes at all, since your values happen fit the requirements for not needing quotes at all).
Upvotes: 3