Reputation: 8457
I have code that looks like this:
<div class="tag">Order # :</div>
<div class="data">
<input type="text" name="oemTeo[<?=$o;?>]" id="o_oemTeo[<?=$o;?>]" value="<?=$vrow['oemTeo'];?>" />
</div>
I want to select (and apply some css to) the <div class="tag">
element directly BEFORE the <div class="data">
element. How would I define that selector using jQuery. I've tried $(this).prev('div .tag')
but it did not work.
Thanks
Upvotes: 0
Views: 80
Reputation: 3239
Since 'div' with class 'tag' is a sibling for 'div' with class 'data', you can use 'siblings()' method as :
$(function(){
var previousElement = $('div.data').siblings('div.tag');
console.log(previousElement);
});
fiddle link: http://jsfiddle.net/jAnS8/1/
Upvotes: 0
Reputation: 630637
Based on comments, since this
refers to your <input>
element, you need to go to the .parent()
<div>
before going to the previous sibling with .prev()
, like this:
$(this).parent().prev("div.tag");
.prev()
works only on sibling elements, and the <div>
you're after isn't a sibling, but rather a sibling of the parent...so you just need to traverse up to that first.
Upvotes: 2
Reputation: 31
have you tried
$('div.data').prev().css('background-color', 'red');
this goes back to figuring out what 'this' is like nick said.
Upvotes: 0
Reputation: 11327
If this
is the div.data
element, just remove the space from your selector (or eliminate the selector altogether):
$(this).prev('div.tag');
...or if you need to select from the DOM, you could do this:
$('div.tag + div.data').prev();
Upvotes: 1