I got a little bit stuck on this piece of code, so I hope you can help me and this question can help others :)
What I want to accomplish is adding a class to a parent().parent() (I don't know how to call it in english) of a span that is on one than more line. To see if the span uses more than one line I've decided to measure the height of the span. If the span is higher than 25px, than I know for sure that it uses more than one line. Than for each span that matches that condition I want to add a class to the parent().parent() so I can style it with css.
My html looks like this:
<li><label><span class="abc-span">a</span><span class="text-that-is-measured">blablablablabla</span></label></li>
<li><label><span class="abc-span">b</span><span class="text-that-is-measured">blablablablabla</span></label></li>
<li><label><span class="abc-span">c</span><span class="text-that-is-measured">blablablablabla</span></label></li>
My script looks like this:
var items = [];
$('span.text-that-is-measured').each(function (i, e) {
items.push($(e));
});
for (var i = items.length - 1; i >= 0; i--) {
console.log(items[i]);
var spanheight = $(items[i]).height();
if ( spanheight > 30) {
$(items[i]).parent().parent().addClass('exampleclass');
}
};
The problem is that is will only give the first li
that matches the condition a class "exampleclass", and I want it to be on each li
Does anybody know what I am doing wrong ?
I hope my explanation was clear enough, english is not my first language.
Thanks in advance!
Thanks everyone for the explanation and help!
You need to use closest
to get the ancestor li
Try this:
$('span.text-that-is-measured').each(function(i, e) {
if ($(this).height() > 30) {
$(this).closest('li').addClass('exampleclass');
}
});