求$('img[alt="Apple Store Logo"]').parent().removeAttr("target")的原生JS实现
No problem at all! Let's walk through how to translate that jQuery snippet into vanilla JS, since you already have a head start on the parent/removeAttribute mappings.
First, the selector part: jQuery's $('img[alt="Apple Store Logo"]') uses standard CSS selector syntax, which works directly with native JavaScript's document.querySelector() (for a single element) or document.querySelectorAll() (for multiple matching elements).
Single Matching Element
If you only expect one <img> with that alt text, use this:
// Grab the target image const appleStoreLogoImg = document.querySelector('img[alt="Apple Store Logo"]'); // Make sure the element exists before modifying its parent (avoids errors) if (appleStoreLogoImg) { appleStoreLogoImg.parentElement.removeAttribute('target'); }
Multiple Matching Elements
If there might be multiple images with that alt text, loop through them all:
// Get all matching images const appleStoreLogoImgs = document.querySelectorAll('img[alt="Apple Store Logo"]'); // Iterate over each image and update its parent appleStoreLogoImgs.forEach(img => { img.parentElement.removeAttribute('target'); });
A quick note: Unlike jQuery, which silently ignores non-existent elements, native JS will throw an error if you try to call parentElement on null (which is what querySelector returns if no match is found). That's why we add the if check in the single-element case—it's a safe practice to avoid runtime bugs!
内容的提问来源于stack exchange,提问作者Tom Ross

