.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
.
Asked
Active
Viewed 1.0k times
28

Przemek
- 3,855
- 2
- 25
- 33
7 Answers
26
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
});

Samich
- 29,157
- 6
- 68
- 77
-
It match these elements but not their values. – Przemek Sep 22 '11 at 16:23
-
Your code matches Something. I just want to match right the "Something" but of all elements with class "class". – Przemek Sep 22 '11 at 16:28
-
2Something like in the second sample? – Samich Sep 22 '11 at 16:31
13
I prefer a one liner:
var fullHtml = $( '<div/>' ).append( $('.class').clone() ).html();

iambriansreed
- 21,935
- 6
- 63
- 79
-
This one would have a side effect, it would try to move the elements of $(".class") to the inside the virtual `div` element, i.e., they would be removed from the actual DOM. You may need to do a `clone()` first, but that would probably too much overhead. – Walty Yeung Oct 07 '15 at 08:49
5
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:

George
- 36,413
- 9
- 66
- 103
5
-
3Code-only answers are considered low quality, make sure to provide an explanation of what your code does and how it solves the problem. – NDBoost Oct 01 '19 at 22:19
1
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.