JAVASCRIPT

Extract All Text Content from Specific Elements

Learn how to traverse the DOM to find all occurrences of specific HTML tags within a given container and efficiently extract their combined text content for processing or display.

function extractTextFromElements(containerId, selector) {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error(`Container with ID '${containerId}' not found.`);
    return [];
  }

  const elements = container.querySelectorAll(selector);
  const textContents = Array.from(elements).map(el => el.textContent.trim());

  return textContents.filter(text => text.length > 0);
}

// Usage example:
// <div id="articleContent">
//   <h1>Article Title</h1>
//   <p>This is the first paragraph of the article.</p>
//   <p>Here is another paragraph with some <b>bold</b> text.</p>
//   <div>
//     <span>An inline span.</span>
//   </div>
// </div>

const paragraphs = extractTextFromElements('articleContent', 'p');
console.log('Paragraphs:', paragraphs); // Output: ['This is the first paragraph of the article.', 'Here is another paragraph with some bold text.']

const headings = extractTextFromElements('articleContent', 'h1');
console.log('Headings:', headings); // Output: ['Article Title']
How it works: This function extracts the text content from all elements matching a specified CSS selector within a particular container. It uses `document.getElementById` to find the parent container and then `container.querySelectorAll(selector)` to retrieve a NodeList of all matching descendant elements. The `Array.from().map()` pattern is used to convert the NodeList into an array and extract the `textContent` from each element. Finally, `trim()` removes leading/trailing whitespace, and `filter()` ensures only non-empty strings are returned, providing a clean array of text content.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs