簡體   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