如何修改document.querySelectorAll选择器以精准选中文本为‘Know More’的指定按钮?
<a> Elements with Exact Text "Know More" Hey there! To narrow down your selection to only those <a> buttons displaying the exact text "Know More", here are two reliable approaches you can use to adjust your code:
Option 1: Use the :contains() CSS Selector
Modern browsers support the :contains() pseudo-class, which lets you target elements containing specific text directly in your querySelectorAll call:
// Select all <a> elements that contain the text "Know More" const buttons = document.querySelectorAll('a:contains("Know More")');
Note:
:contains()is case-sensitive, so it will only match text that exactly matches the case you specify. If you need case-insensitive matching, you’ll want to use the filter method below instead.
Option 2: Filter Elements by Text Content (More Flexible)
For greater control—like handling accidental whitespace around the text or case insensitivity—use Array.from() to convert the NodeList to an array, then filter based on the element’s text content:
// Convert NodeList to array, then filter for exact trimmed text match const buttons = Array.from(document.querySelectorAll('a')).filter(btn => btn.textContent.trim() === 'Know More' );
The trim() here ensures any leading/trailing spaces in the button text won’t break the match, which is handy if your HTML has unintended whitespace.
Updated Full Code
Here’s your original code modified with the second (more robust) approach:
const buttons = Array.from(document.querySelectorAll('a')).filter(btn => btn.textContent.trim() === 'Know More'); buttons.forEach(btn => { btn.addEventListener('click', function(e) { var totalOffsetX = 0; // X and Y COORDINATES WITH SCROLL START var totalOffsetY = 0; var X = 0; var Y = 0; var currentElement = this; do { totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft; totalOffsetY += currentElement.offsetTop - currentElement.scrollTop; } while (currentElement = currentElement.offsetParent) X = e.pageX - totalOffsetX; Y = e.pageY - totalOffsetY; // X and Y COORDINATES WITH SCROLL END let ripples = document.createElement('buttonspan'); ripples.style.left = X + 'px'; ripples.style.top = Y + 'px'; this.appendChild(ripples); setTimeout(() => { ripples.remove() }, 1000); }) })
This will only attach the click event listener to your two "Know More" buttons, ignoring any other <a> elements on the page.
内容的提问来源于stack exchange,提问作者alexeugenehunt

