jQuery: how to address a sub item with a special class
-
27-10-2019 - |
Question
I want to iterate over the line elements. Each line element has item elements as child elements. So first I iterate over line and then I want to address a certain item element e.g. the third. This is the code I have:
$(".pricetable .righttable .line:not(.blank)").each(function(j) {
var currentLine = $(".pricetable .righttable .line:not(.blank)").eq(j);
currentLine.(".item").each(function(k) {
$(".pricetable .righttable .line .item").eq(i).addClass("active");
});
});
The problem is that I don't know how to address the child element with the item class.
currentLine.(".item").each(function(k)
This does not work.
XML filter is applied to non-XML value ({0:#2=({}), length:1, prevObject:{length:3, prevObject:{0:#1=({}), context:#1#, length:1}, context:#1#, selector:".pricetable .righttable .line:not(.blank)", 0:#2#, 1:({}), 2:({})}, context:#1#, selector:".pricetable .righttable .line:not(.blank).slice(0,1)"}) file:///C:/Users/xxx/lib/pricetable.js Line 112
Edit:
Wow, I didn't thought I get such a good and fast response! I think I go with this solution:
$(".pricetable .righttable .line:not(.blank)").each(function(j) {
$(this).children(".item").eq(i).addClass("active");
});
Solution
$(".pricetable .righttable .line:not(.blank)").each(function(j) {
var currentLine = $(".pricetable .righttable .line:not(.blank)").eq(j);
currentLine.find(".item").each(function(k) {
$(".pricetable .righttable .line .item").eq(i).addClass("active");
});
});
If they're direct children of currentLine, you should just be able to do children('.item')
in place of find('.item')
. This is called Traversing the DOM. Visit this page (http://api.jquery.com/category/traversing/) and read through the descriptions of some of the functions there. They'll be very useful to keep in mind if you traverse a lot :)
OTHER TIPS
$('.pricetable .righttable .line:not(.blank)').find('.item').each(function() {
// this point to child element - item
// use $(this).addClass('active');
});
Slight improvement before I answer your question:
var currentLine = $(".pricetable .righttable .line:not(.blank)").eq(j);
is easily replaceable with:
var currentLine = $(this);
Second, if you wish to find the 3rd .item
element inside of $(this)
, use .find()
.find(".item:nth-child(3)");
No need to iterate over the lines. If you must iterate over the lines, then just compare k
to 2
(As JavaScript counts from 0) and that's it.
If you want to do something with the nth item
of each line
, it's much easier than it looks:
var index = 3; // the third "item" element
$(".pricetable .righttable .line:not(.blank) .item:nth-child(" + index + ")")
.addClass("active");
Is there something else you want to do that the above is not sufficient for?
$(".pricetable .righttable .line:not(.blank)").each(function() {
$(this).find('.item:nth-child(2)').addClass('active');
});