简体   繁体   中英

jQuery .html() of all matched elements

.html() function on class selector ( $('.class').html() ) applies only to the first element that matches it. I'd like to get a value of all elements with class .class .

You are selection all elements with class .class but to gather all html content you need to walk trough all of them:

var fullHtml;

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

search items by containig text inside of it:

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

Code: http://jsfiddle.net/CC2rL/1/

我更喜欢一个班轮:

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

You could map the html() of each element in a filtered jQuery selection to an array and then join the result:

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

Documentation:

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

In case you require the whole elements (with the outer HTML as well), there is another question with relevant answers here : Get selected element's outer HTML

A simple solution was provided by @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 );

An even simpler solution by @Eric Hu . Note that not all browsers support outerHTML :

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

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

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

I am posting the link to the other answer and what worked for me because when searching I arrived here first.

Samich Answer is correct. Maybe having an array of html s is better!

var fullHtml = [];

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

If you turn your jQuery object into an Array you can reduce over it.

const fullHtml = $('.class')
   .toArray()
   .reduce((result, el) => result.concat($(el).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