简体   繁体   中英

How to get only the first list element in menu of unordered list in JQuery?

I need to get the first element in the list of unordered lists. I used bellow code and getting all list items as output. Then I click f12 and executed this code [image description output of this code][1] [1]: https://i.stack.imgur.com/OZ4qn.png jQuery(window).resize(function() {

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="style.css">
<script>
jQuery(document).ready(function(){
setTimeout(function(){
jQuery(window).resize(function() {
jQuery(".mean-nav>ul>li:first").click(function(){
  alert(jQuery(this).text());
   });
    });
     },2000);
});

</script>

  </head>
<body>
<div>
 <!--<div class="leader1">REgister</div>
 <div class="leader2">Login</div>
  <div class="leader3">Call Us</div>-->
   <div class="mean-nav">
    <ul>
     <li>1
     <ul>

        <li> aa</li>
        <li> bb</li>
        <li> cc</li>
        <li> dd</li>
        <li> ee</li>
    </ul>
    </li>
      <li>2</li>
      <li>3</li>
       <li>4</li>
       <li>5</li>
       </div>
     </div>
</body>
</html>

As Wax already mentioned, using a selector combination of

$('.mean-nav > ul > li:first-child').click(function() {
    ...
});

will search for every element containing the class mean-nav , inside search for a directly following ul and inside search for a directly following li , but only the first occurence is going to be handled. :first-child provides the same functionality it's JavaScript equivalent :nth-child(1) does.

However, the :first-child selector is able to find multiple elements, so if you had multiple ul inside your element with mean-nav containing at least one li each, you would find multiple elements.

The :first selector does something different - it finds the first occurence of your selector and stops right after - without the risk of finding multiple elements.

Applying that to an example:

[...]
<div class="mean-nav">
    <ul>
        <li>ASDF</li>
        <li>BDGF</li>
    </ul>
</div>
<div class="mean-nav">
    <ul>
        <li>2345</li>
        <li>9887</li>
    </ul>
</div>
[...]

in this example, using both selectors you would get the following results:

$('.mean-nav > ul > li:first-child').click(function() {
    console.log($(this).html());
});

would log into console two times: 'ASDF' and '2345' - while

$('.mean-nav > ul > li:first').click(function() {
    console.log($(this).html());
});

would only log once: 'ASDF'.

In your case :first-child works just the way :first would, but best practice would probably be to use :first , as you want to find a single element only anyways.

Edit: in your original post, you are not closing the <ul>

Edit 2: remember that the > selector searches for directly following elements, so you cannot find nested elements unless you leave the > step out or specify the selection

Edit 3: as op wants to select the 1 in his ul only, without the appended ul, which is still part of the li containing 1, I believe he has to hack this a little bit:

$(function() {
    console.log($('.mean-nav > ul > li:first').text().replace($('.mean-nav > ul > li:first > ul').text(), '').trim());
});

Let's rip this apart:

  • console.log logs into the console
  • $('.mean-nav > ul > li:first').text() returns 1 aa bb cc ddee with a lot of whitespace
  • x.replace(y, z) replaces each occurence of y with z in x
  • $('.mean-nav > ul > li:first > ul').text() returns aa bb cc ddee with a lot of whitespace
  • x.trim() removes all newlines, spaces and tabs at the start and end of a string

So what this does is cut the content of the ul inside your li:first out of the content of your li:first , leaving you with, in this example, 1

$('.mean-nav ul li:first').click(function(){
   //Do your stuff
});

You can also target other children using nth-child(n). For eg.,

$('.mean-nav ul li:nth-child(2)').click(function(){
   //Do your stuff
});

Try this:

1) $(".mean-nav > ul> li:first-child")

OR

2) $(".mean-nav > ul> li:nth-child(1)")

OR, If you want select first li

3) $(".mean-nav > ul > li:nth-of-type(1)")

To access the first li of ul you need first-child selector

jQuery(".mean-nav>ul>li:first-child").click(function(){
  alert(jQuery(this).text());
   });
    });
     },2000);
});

Use nth-first for get only first element.

jQuery(".mean-nav>ul>li:first").click(function(){});

Please Check after resize window.

 jQuery(document).ready(function(){ jQuery(window).resize(function() { jQuery(".mean-nav>ul>li:first").click(function(){ alert(jQuery(this).text()); return false; }); }); }); 
 <!DOCTYPE html> <html lang="en"> <head> <title>Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <div> <!--<div class="leader1">REgister</div> <div class="leader2">Login</div> <div class="leader3">Call Us</div>--> <div class="mean-nav"> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </div> </div> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM