如何使用原生JavaScript仅在父div含指定类时为<img>添加类?
Add Class to Images Inside Parent Divs with "box" Class (Vanilla JS)
Got it! Let's break down how to target those <img> tags whose parent <div> has the box class and add a custom class to them using plain Vanilla JavaScript.
Approach
We’ll follow these straightforward steps:
- Select all
<div>elements that include theboxclass. - For each of these divs, locate all
<img>elements nested inside. - Apply your desired class to every targeted image.
- Ensure the code runs after the DOM is fully loaded to avoid trying to manipulate elements that haven’t rendered yet.
Complete Code Example
First, here’s your sample HTML for reference:
<div class="example first"> <h2><a>sample text</a></h2> <img src="./img/sample.png" /> <p>sample text</p> </div> <div class="example box"> <h2><a>sample text</a></h2> <img src="./img/sample.png" /> <p>sample text</p> </div>
Now the JavaScript to add the class (replace img-inside-box with your actual class name):
// Wait for the DOM to finish loading before executing code document.addEventListener('DOMContentLoaded', () => { // Grab all divs that have the "box" class const boxContainers = document.querySelectorAll('.box'); // Loop through each box container boxContainers.forEach(container => { // Find all img elements inside the current container const images = container.querySelectorAll('img'); // Add the target class to each image images.forEach(img => { img.classList.add('img-inside-box'); }); }); });
What This Does
document.querySelectorAll('.box'): Captures every div with theboxclass (in your example, only the second div qualifies).container.querySelectorAll('img'): For each box div, finds all images inside it—this works even if there are multiple images in one box.img.classList.add('img-inside-box'): Adds your specified class to each targeted image. After running this, the second<img>tag will have theimg-inside-boxclass, while the first one won’t.
Simplified Version (If Each Box Has Only One Image)
If you know each box div will only ever contain one <img>, you can shorten the code to this more concise form:
document.addEventListener('DOMContentLoaded', () => { // Directly select all imgs inside .box divs and add the class document.querySelectorAll('.box img').forEach(img => { img.classList.add('img-inside-box'); }); });
This directly targets all <img> elements that are descendants of a .box div, then applies the class to each. It’s cleaner and works perfectly for single-image boxes.
内容的提问来源于stack exchange,提问作者KAindex
相关产品推荐
相关产品推荐

