how to get content of all <li> tags in one page using jquery

瘦欲@ 提交于 2019-12-31 04:11:12

问题


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

回答1:


You can use jQuery.map()

Live Demo

texts = $('li').map(function(){
  return $(this).text();
}).get().join(',');



回答2:


var $tags = $("li").map(function(){
  return $(this).text();
}).get().join(",");

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




回答3:


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(",");


来源:https://stackoverflow.com/questions/15977789/how-to-get-content-of-all-li-tags-in-one-page-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!