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

如何用JavaScript批量替换HTML中href与img链接的指定路径片段

Hey there! Let's get this sorted so you can update all 200+ image links in one go—no manual edits required.

Why Your Current Code Only Works for the First Group

The core issue here is invalid HTML practice: IDs must be unique across an entire page. When you use document.getElementById('ChanglingIDhref') or getElementById('ChanglingIDimg'), the browser only returns the first element with that ID. That's why your changes never reach the second, third, or any subsequent div groups.

The Fix: Traverse All Target Elements

Instead of relying on duplicate IDs, we can use selectors that target all relevant links and images. Here are two straightforward approaches:

Approach 1: Target Elements by Their Attribute Content

This selects every <a> tag whose href contains "fileortname" and every <img> tag whose src includes the same string:

// Update all a tags with href containing "fileortname"
document.querySelectorAll('a[href*="fileortname"]').forEach(link => {
  link.href = link.href.replace("fileortname", x);
});

// Update all img tags with src containing "fileortname"
document.querySelectorAll('img[src*="fileortname"]').forEach(img => {
  img.src = img.src.replace("fileortname", x);
});

Approach 2: Use the Existing Class to Group Elements

Since all your image links share the photo-item class, we can target those directly and update both the link and its nested image in a single loop:

// Loop through each photo-item link
document.querySelectorAll('.photo-item').forEach(photoLink => {
  // Update the link's href
  photoLink.href = photoLink.href.replace("fileortname", x);
  
  // Find the nested img tag and update its src
  const img = photoLink.querySelector('img');
  if (img) {
    img.src = img.src.replace("fileortname", x);
  }
});

Quick Best Practice Reminder

Always avoid reusing IDs in HTML—it violates web standards and leads to unpredictable behavior with JavaScript and CSS. For groups of elements, stick to classes or attribute selectors like we did here.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:26:36