Daniel Moss
Daniel Moss

Reputation: 567

How do I use a dynamic selector in ".length" property?

I have this HTML code:

<ul class="bookings-layout3">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
<ul>

And this JS code that works to return the length (4, in this case) of the ul, but the selector is hard-coded:

function getLength() {
    console.log($(".posts-layout5 li").length);
}

But I would like to make the function re-usable by being able to input an argument of the targeted class and not just hard-code it, like this:

function getLength(ul_to_target) {
    console.log($(".{ul_to_target} li").length);
}

How can I go about this?

Upvotes: 0

Views: 102

Answers (1)

David
David

Reputation: 218837

If ul_to_target is just a string, you would use the + operator to concatenate strings. For example:

console.log($("." + ul_to_target + " li").length);

Though the variable name may be misleading in this regard. The usage implies that it's a string, but the name implies that it's an element. If ul_to_target is an actual element (or jQuery object wrapping an element) and you want to specifically query descendants of that element for li elements, it would look something like this:

console.log($("li", ul_to_target).length);

Variable names are important. Maybe it should be something like ul_class instead?

Upvotes: 2

Related Questions