如何检测picture标签中media为450px的source并修改其srcset值
Solution to Detect and Update Target
<source> Element in <picture> Hey there! Let's break down how to detect the specific <source> element you're targeting and update its srcset attribute using vanilla JavaScript—no external libraries needed.
Step 1: Locate the Target Source Element
First, we'll use a precise CSS selector to find the <source> element inside your <picture class="pic_test"> tag that has the media attribute set to (min-width:450px). Here's how to select it:
const targetSource = document.querySelector('picture.pic_test source[media="(min-width:450px)"]');
picture.pic_testnarrows down to the specific<picture>tag with the classpic_testsource[media="(min-width:450px)"]targets the<source>element with the exactmediaattribute value you're looking for
Step 2: Verify Existence and Update srcset
Always check if the element exists before modifying it to avoid console errors. Once confirmed, you can update the srcset attribute with your desired image path:
// Wait for the DOM to fully load before executing (recommended) document.addEventListener('DOMContentLoaded', function() { const targetSource = document.querySelector('picture.pic_test source[media="(min-width:450px)"]'); if (targetSource) { // Replace "updated-450px-image.jpg" with your actual image URL/path targetSource.srcset = "updated-450px-image.jpg"; console.log("Successfully updated the srcset for the 450px+ media query!"); } else { console.log("No source element with media '(min-width:450px)' found in the picture tag."); } });
Key Notes
- Wrapping the code in
DOMContentLoadedensures it runs only after all HTML elements are rendered, so you won't try to select an element that hasn't loaded yet. - If you need to run this code dynamically (e.g., after a button click or AJAX load), you can remove the
DOMContentLoadedlistener and call the selection/update logic directly in your event handler.
内容的提问来源于stack exchange,提问作者robert
相关产品推荐
相关产品推荐

