how to get content of all
  • tags in one page us
  • 2020-04-22 04:52发布

    I have an html list something like this:

    <li id="tag">red</li>
    <li id="tag">yellow</li>
    <li id="tag">blue</li>
    

    How can I get the content of these li tags using jQuery?

    For example;

    $tags = red, yellow, blue
    

    3条回答
    贼婆χ
    2楼-- · 2020-04-22 05:14

    First, you should change your id="tag" to class="tag", as you can't have multiple elements with the same id.

    You can build an array of the values:

    var content = [];
    $("li").each(function (element) {
        content.push[$(element).text()];
    });
    

    Or as others have pointed out, you can use map:

    var content = $("li").map(function() {
        return $(this).text();
    }).get().join(",");
    
    查看更多
    Evening l夕情丶
    3楼-- · 2020-04-22 05:25
    var $tags = $("li").map(function(){
      return $(this).text();
    }).get().join(",");
    

    Here, have a fiddle: http://jsfiddle.net/KTted/2/

    查看更多
    老娘就宠你
    4楼-- · 2020-04-22 05:29

    You can use jQuery.map()

    Live Demo

    texts = $('li').map(function(){
      return $(this).text();
    }).get().join(',');
    
    查看更多
    登录 后发表回答