jQuery class selector - can I target two items?

时间:2015-07-13 21:07:41

标签: javascript jquery

Say for example, you have this HTML code:

<ul>
   <li class="hello">Hello</li>
</ul>

<h1 class="hello">Hello<h1>

If I accompany it by the following jQuery, then the .hello class text will he changed to "hello", instead of "Hello":

$(document).ready(function() {
    $(".hello").text("hello");
});

My question is, what if I wanted to target the .hello class within the li only, would I then be able to reconstruct the above code to something like this?:

$(document).ready(function() {
    $("li .hello").text("hello");
});

Furthermore, if that DOES work, what is the limit of items allowed, or is it similar to CSS in that you can sort of nest as many items as you want, such as body header .li:nth-child(1)?

Keep in mind, I am learning jQuery for the first time while asking this question and don't have an editor to test it out at the moment.

4 个答案:

答案 0 :(得分:5)

No $("li .hello").text("hello"); (noting the space between the element and class) looks for an element with the class of hello that is a descendant of the list item.

To select the list item with the class of hello, use:

$("li.hello").text("hello");

Note no spaces between the li element and the class hello, just the period.

In jQuery (and CSS) there's more than one way to skin a cat, so for example another way to select the list item and not the heading is:

$("ul .hello").text("hello");

or

$("ul li.hello").text("hello");

jQuery's selector system was actually modeled after CSS selectors.

答案 1 :(得分:2)

To target just the hello class for li don't have a space

$(document).ready(function() {
    $("li.hello").text("hello");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<ul>
   <li class="hello">Hello</li>
</ul>

<h1 class="hello">Hello<h1>

答案 2 :(得分:1)

You are on the right track but do not include a space

$(document).ready(function() {
    $("li.hello").text("hello");
});

The space is valid if you wanted to select children elements of li with .hello. Without a space, you are selecting li elements with .hello

答案 3 :(得分:1)

此问题的另一个好方法是使用不同的类。

通过这种方式,您可以将HTML与HTML分离,并使其更易于维护。

例如:

<li class='js-hello'> </li>

现在它与哪个元素无关。您拥有更高效,更易于使用,更清晰,更便携的前端代码。

这可以帮助您解决第二个问题。答案是肯定的,你可以深入了解类似$('body header nav ul li.hello')之类的东西,但不是真的可取,因为它与HTML结构紧密相关,浏览器解释的工作量更多,下一个开发人员更难理解和更难在代码中的其他地方重复使用。