如何点击包含SVG元素的span标签内的按钮?技术求助
Based on the HTML structure you provided, here are reliable ways to trigger a click on the button containing the SVG with aria-label="WANT TO CLICK". The differing classes on parent <span> elements won’t affect these solutions—we’re targeting the specific elements you care about directly.
Vanilla JavaScript Solutions
Click a Single Target Button
This approach uses the unique aria-label on the SVG to find the exact button you want:
// Wait for the DOM to fully load before running the code document.addEventListener('DOMContentLoaded', () => { // Locate the SVG with the specific aria-label const targetSvg = document.querySelector('svg[aria-label="WANT TO CLICK"]'); if (targetSvg) { // Traverse up to the parent button element const targetButton = targetSvg.closest('button'); if (targetButton) { targetButton.click(); console.log('Button clicked successfully!'); } else { console.error('Could not find the parent button for the target SVG.'); } } else { console.error('SVG with aria-label "WANT TO CLICK" not found in the DOM.'); } });
Click All Matching Buttons
If there are multiple buttons with the same SVG aria-label and you want to click all of them:
document.addEventListener('DOMContentLoaded', () => { const targetSvgs = document.querySelectorAll('svg[aria-label="WANT TO CLICK"]'); targetSvgs.forEach(svg => { const button = svg.closest('button'); if (button) button.click(); }); console.log(`Clicked ${targetSvgs.length} matching buttons.`); });
jQuery Solution (If You’re Using jQuery)
If your project uses jQuery, this one-liner will do the trick:
$(document).ready(() => { $('svg[aria-label="WANT TO CLICK"]').closest('button').click(); });
Key Notes
- Why parent
<span>classes don’t matter: Our selectors target the SVG directly (via itsaria-label) or the button, so the class of the parent<span>is irrelevant here. Even if other spans have different classes, this code will only interact with the button containing the SVG with your targetaria-label. - Dynamic elements: If the button loads after the initial page load (e.g., via AJAX), you’ll need to run the code after the element is added to the DOM, or use a mutation observer to detect when it appears.
内容的提问来源于stack exchange,提问作者Rishabh Anand
相关产品推荐
相关产品推荐

