How to I use jQuery to identify selectors that I need?
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 di开发者_Python百科d not work.
Thanks
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.
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();
have you tried
$('div.data').prev().css('background-color', 'red');
this goes back to figuring out what 'this' is like nick said.
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/
精彩评论