繁体   English   中英

所有匹配元素的 jQuery .html()

[英]jQuery .html() of all matched elements

类选择器( $('.class').html() )上的.html()函数仅适用于与其匹配的第一个元素。 我想用 class .class获得所有元素的值。

您正在选择具有类.class的所有元素,但要收集所有 html 内容,您需要遍历所有元素:

var fullHtml;

$('.class').each(function() {
   fullHtml += $(this).html();
});

通过其中包含的文本搜索项目:

$('.class:contains("My Something to search")').each(function() {
   // do somethign with that
});

代码:http: //jsfiddle.net/CC2rL/1/

我更喜欢一个班轮:

var fullHtml = $( '<div/>' ).append( $('.class').clone() ).html();

您可以将过滤后的 jQuery 选择中每个元素的html()映射到一个数组,然后加入结果:

           //Make selection
var html = $('.class')
          //Filter the selection, returning only those whose HTML contains string 
          .filter(function(){
              return this.innerHTML.indexOf("String to search for") > -1
          })
          //Map innerHTML to jQuery object
          .map(function(){ return this.innerHTML; })
          //Convert jQuery object to array
          .get()
          //Join strings together on an empty string
          .join("");

文档:

$('.class').toArray().map((v) => $(v).html())

如果您需要整个元素(以及外部 HTML),这里还有一个相关答案的问题: 获取所选元素的外部 HTML

@Volomike提供了一个简单的解决方案

var myItems = $('.wrapper .items');
var itemsHtml = '';

// We need to clone first, so that we don’t modify the original item
// Thin we wrap the clone, so we can get the element’s outer HTML
myItems.each(function() {
    itemsHtml += $(this).clone().wrap('<p>').parent().html();
});

console.log( 'All items HTML', itemsHtml );

@Eric Hu的一个更简单的解决方案 请注意,并非所有浏览器都支持outerHTML

var myItems = $('.wrapper .items');
var itemsHtml = '';

// vanilla JavaScript to the rescue
myItems.each(function() {
    itemsHtml += this.outerHTML;
});

console.log( 'All items HTML', itemsHtml );

我正在发布指向另一个答案的链接以及对我有用的方法,因为在搜索时我首先到达了这里。

Samich答案是正确的。 也许拥有一个html数组会更好!

var fullHtml = [];

$('.class').each(function() {
   fullHtml.push( $(this).html() );
});

如果你把你的 jQuery 对象变成一个Array ,你可以减少它。

const fullHtml = $('.class')
   .toArray()
   .reduce((result, el) => result.concat($(el).html()), '')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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