Gust van de Wal Gust van de Wal - 1 month ago 5
jQuery Question

Selecting element after 'this'

I need to select multiple elements at once for a function. I've got

jQuery

$('[class^="shapeLeft"]').click(function(){
var $parent = $(this).parent()
var $both = $(this, 'this + div[class^="shapeRight"]')
$both.css({'height': parent.height() + 20})
})


HTML

<div class="shapeLeftDiamond"></div>
<div class="shapeRightDiamond"></div>


The part where I say
$(this, 'this + div[class^="shapeRight"]')
doesn't seem to work.
The clicked element does get its height changed, but its direct neighbor with a class starting with
shapeRight
doesn't.

How do I select the clicked element and its
shapeRight
sibling at once?

Thanks

Answer

Either use .next() if it is the exact following node

var thisShape = $(this).next().addBack();

or use .siblings() if they share the same parent but might have other elements in the DOM between them

var thisShape = $(this).siblings('[class^="shapeRight"]').addBack();

In both cases you alse need to add the .addBack() at the end, to include the current element in the selection (the this in your case)

Demo at https://jsfiddle.net/gaby/qukkwvL1/3/

Comments