如何获取class为fast且包含文本big的元素内部span标签的id属性
Solution to Get Span ID from Specific .fast Elements
First, let's break down why your original code wasn't working:
document.getElementsByClassName("fast")returns an HTMLCollection (a list of elements), not a single element. Trying to accesselems.innerHTMLdirectly on this collection will returnundefined.xxends up as a boolean (true/false) because you're checking ifindexOf('full') > -1. Booleans don't have a.lengthproperty, so your loop never runs.- Even if
xxwere a valid list, you're repeatedly targetingxx[0]in the loop, which would only ever grab the first element.
Now here's a working approach to get the span's id from elements with class fast that contain the text "big":
Option 1: Modern DOM Methods (Recommended)
This uses querySelectorAll for cleaner selection and forEach to loop through elements:
// Grab all elements with class "fast" const fastElements = document.querySelectorAll('.fast'); // Loop through each .fast element fastElements.forEach(element => { // Check if the element contains the text "big" if (element.textContent.includes('big')) { // Find the span inside this element const targetSpan = element.querySelector('span'); if (targetSpan) { // Get and use the span's id const spanId = targetSpan.id; // Shorthand for getAttribute('id') alert(spanId); // Replace with your desired action } } });
Option 2: Legacy Browser Support
If you need to support older browsers without forEach on NodeLists, use a traditional for loop:
// Get all .fast elements (returns an HTMLCollection) const fastElements = document.getElementsByClassName('fast'); // Loop through the collection for (let i = 0; i < fastElements.length; i++) { const currentElement = fastElements[i]; // Check for the "big" text if (currentElement.textContent.includes('big')) { // Find the first span in the element const targetSpan = currentElement.getElementsByTagName('span')[0]; if (targetSpan) { const spanId = targetSpan.getAttribute('id'); alert(spanId); } } }
Important Notes:
- Invalid HTML: Your original HTML has
<div>and<span>directly inside<tr>elements, which is not valid.<tr>should only contain<td>or<th>elements. Fixing this will prevent unexpected DOM behavior. - Precise Text Matching: If you need to target a specific child div with exactly the text "big" (not just any occurrence), adjust the check to:
// Check for a div with exact text "big" const bigDiv = Array.from(currentElement.getElementsByTagName('div')).find(div => div.textContent.trim() === 'big'); if (bigDiv) { // Proceed to get the span id }
内容的提问来源于stack exchange,提问作者pierrejeanes




