Reputation: 45124
Please help me out with the following code. I don't understand it. I have to use a snippet like this in my project.
$('strong', this)
<- this part is not clear to me at all.
Please be kind enough to explain the whole code line by line if possible.
<ul>
<li><strong>list</strong> item 1 -
one strong tag
</li>
<li><strong>list</strong> item <strong>2</strong> -
two <span>strong tags</span>
</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
JavaScript:
$('li').filter(function(index) {
return $('strong', this).length == 1;
}).css('background-color', 'red');
Upvotes: 0
Views: 129
Reputation: 1787
The code is basically getting a list of li elements using the jQuery $('li')
(this will get all <li> ... </li>
tags on the page)
It then reduces this set with the .filter
function, filter
takes a function as an argument, the function is called on each element in the list, if it returns true the element is returned in the list from filter if it return false the item is ignored.
In this context the function calls $('strong', this).length == 1
where this
is the li tag that currently being decided checked by the filter, as mentioned in other answers it's simply checking returning the list of <strong>..</strong>
tags in the current li. If there is not strong in the current li, length is 0 so the function returns false
, this means the filter wont return that element in the list it produces, it then moves on to the next li.
this means the the first part of the code simply produces a list of li's with a strong tag in them, this is then chained with the css
function which colours all those tags in red.
Hope that helps.
Upvotes: 1
Reputation: 87073
$('strong', this)
is jQuery selector with $(target, context)
format.
According to your code:
this
refers to li
and $('strong', li)
is searching a <strong>
that within that li
tag.
This statement can also be written as:
$(this).find('strong')
and from jQuery library code you'll see that:
$(target, context)
format internally implement the
$(context).find(target)
process.
Upvotes: 1