Using jQuery to Get All Elements by Class Name and Concatenate Their Content

Nov 23, 2025 · Programming · 7 views · 7.8

Keywords: jQuery | class selection | element content concatenation

Abstract: This article explores how to use jQuery's .map() method to retrieve the content of all elements with the same class name and concatenate them into a string. By comparing native JavaScript and jQuery approaches, it analyzes the principles and performance of core functions like .map() and .each(), providing complete code examples and best practices to help developers efficiently handle DOM element collections.

Problem Background and Core Challenge

In web development, it is common to manipulate multiple DOM elements with the same class name. For instance, a user may want to fetch the inner HTML content of all <div> elements with the class mbox and join them into a comma-separated string. An initial attempt using $('.mbox').html() only returns the content of the first matching element, as jQuery's .html() method, when applied to multiple elements, defaults to operating on the first one.

Solution with jQuery's .map() Method

jQuery's .map() method offers an efficient way to iterate over a set of elements and return a new array. The core principle involves executing a callback function for each matched element, collecting the return values, and converting the jQuery object to a plain JavaScript array using .get(). The following code demonstrates this approach:

var all = $(".mbox").map(function() {
    return this.innerHTML;
}).get();
console.log(all.join(", "));

In this example, $('.mbox') selects all elements with the class mbox. The .map() method iterates over each element, with the callback function returning this.innerHTML (i.e., the inner HTML of the element). .get() converts the result to an array, and .join(', ') concatenates the array elements into a string with commas and spaces. This method avoids the complexity of direct DOM manipulation, enhancing code readability and maintainability.

Comparison with Other Methods: The .each() Function

Aside from .map(), jQuery's .each() method can also be used for iteration. The code is as follows:

var mvar = "";
$(".mbox").each(function() {
    mvar += $(this).html();
});
console.log(mvar);

.each() processes each element individually and appends the content to a string variable. However, this approach may be slightly less performant than .map() due to multiple string concatenations, which can lead to unnecessary memory allocations. For large datasets, .map() is generally more efficient as it directly returns an array, facilitating further processing.

In-Depth Analysis: .map() vs. Native JavaScript

From an implementation perspective, jQuery's .map() method wraps native JavaScript array mapping logic while providing cross-browser compatibility. For example, the native approach uses document.querySelectorAll('.mbox') to get elements and then applies Array.prototype.map:

var elements = document.querySelectorAll('.mbox');
var all = Array.prototype.map.call(elements, function(el) {
    return el.innerHTML;
});
console.log(all.join(", "));

Although native methods may offer better performance, jQuery simplifies the code, especially for handling compatibility issues. In practice, choose the appropriate method based on project requirements: use native approaches for maximum performance in modern environments, or jQuery for a more consistent experience.

Best Practices and Considerations

When outputting results, it is advisable to use console.log instead of document.write, as the latter can overwrite the entire document and disrupt page structure. For debugging, the browser console is an ideal tool. Additionally, ensure the HTML structure is correct, such as all target elements having the same class name, to avoid selector errors. For dynamic content, consider using event delegation or MutationObserver to optimize performance.

Conclusion

Using jQuery's .map() method enables efficient retrieval and concatenation of content from multiple class-based elements. This article compared different methods, emphasizing code simplicity and performance trade-offs. Developers should master these core concepts to enhance the interactivity and maintainability of web applications. In real-world scenarios, select the optimal solution based on context and adhere to best practices, such as avoiding document.write.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.