You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测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_test narrows down to the specific <picture> tag with the class pic_test
  • source[media="(min-width:450px)"] targets the <source> element with the exact media attribute 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 DOMContentLoaded ensures 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 DOMContentLoaded listener and call the selection/update logic directly in your event handler.

内容的提问来源于stack exchange,提问作者robert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:00:55