more navigating the dom help
开发者_如何学PythonI'm currently in the sumMe row, how do I access the block1a updateMe class with JQuery?
<div class='headerBlock'>
<div class='block1'>
<div class='block1a'>
<label class='updateMe'> </label>
</div>
</div>
<div class='block2'>
<div class='head'>
<div class='title'>
<div class='sumMe'>$1.01</div>
</div>
</div>
<div class='head'>
<div class='title'>
<div class='sumMe'>$2.01</div>
</div>
</div>
</div>
</div>
This selector will do it.
$(".block1a .updateMe")
Use
$('.block1a .updateMe').text();
$(.....).closest('.headerBlock').find('.updateMe');
$(".block1a label.updateMe")
will give you the required element.
you can select the element using .closest()
or .parents()
to get up to <div class='headerBlock'>
then find the <label class="updateMe">
but you're likely better off just selecting it on it's own (and based on this jsperf it is faster to use a new selector vs trying to find it starting at one of the .sumMe
elements)
here's a possible approach if I'm guessing right on what you're trying to do:
var $updateMe = $('.block1a .updateMe'), // or just $('.updateMe') if there are no others with that class
$sumMe = $('.sumMe'),
sum = 0;
$sumMe.each(function() {
var $that = $(this);
sum += someConvertToFloatFunction($that.text());
});
$updateMe.text(someConvertToDollarFormatFunction(sum));
UPDATED
if there are multiple .headerBlock
elements you can use the above wrapped in a .each
function for the .headerBlock
s and use the current .headerBlock
as a context for the selectors.
$('.headerBlock').each(function() {
var $that = $(this),
$updateMe = $('.block1a .updateMe', $that), // use $that as a context for the selector
$sumMe = $('.sumMe', $that), // use $that as a context for the selector
sum = 0;
$sumMe.each(function() {
sum += someConvertToFloatFunction($(this).text());
});
$updateMe.text(someConvertToDollarFormatFunction(sum));
});
if you're summing the .sumMe
elements (in a given .headerBlock
) as a one-off, then probably using .closest()
as mentioned in @Ariel's answer is a good way to go.
精彩评论