如何用JavaScript判断SVG中<use>元素的href引用是否存在
判断SVG
要判断<use>元素的href指向是否真实存在,得分两种情况处理——同一文档内的引用和外部SVG文件的引用:
一、同一文档内的SVG引用判断
如果<use>指向的是当前HTML文档里定义的SVG元素(比如<defs>里的符号),直接用DOM查询就能搞定:
- 获取
<use>元素的目标ID:先拿到href属性值,提取#后面的部分(比如my-fancy-icon)。 - 用
document.getElementById()或者document.querySelector()查找这个ID对应的元素,返回结果不为null就说明存在。
代码示例:
const useElement = document.querySelector('use'); // 兼容新旧浏览器,优先取href,再取xlink:href const hrefValue = useElement.getAttribute('href') || useElement.getAttribute('xlink:href'); if (!hrefValue) { console.log('没有设置href属性'); return; } // 提取片段ID(#后面的部分) const targetId = hrefValue.split('#')[1]; if (!targetId) { console.log('href格式不正确,缺少片段标识符'); return; } // 查询目标元素 const targetElement = document.getElementById(targetId); if (targetElement) { console.log('目标元素存在'); } else { console.log('目标元素不存在'); }
二、外部SVG文件的引用判断
如果<use>指向的是外部SVG文件(比如assets/icons.svg#my-fancy-icon),需要先加载外部文件再检查:
- 拆分href,分离出外部文件路径和目标ID。
- 用Fetch API加载外部SVG文件,注意处理跨域问题(如果文件不在当前域名下,服务器需要配置CORS)。
- 将加载的内容解析为XML文档,然后在里面查找目标ID对应的元素。
代码示例:
const useElement = document.querySelector('use'); const hrefValue = useElement.getAttribute('href') || useElement.getAttribute('xlink:href'); if (!hrefValue) { console.log('没有设置href属性'); return; } // 拆分文件路径和目标ID const [filePath, targetId] = hrefValue.split('#'); if (!filePath || !targetId) { console.log('href格式不正确'); return; } // 加载外部SVG文件 fetch(filePath) .then(response => { if (!response.ok) { throw new Error('外部SVG文件加载失败'); } return response.text(); }) .then(svgText => { // 创建XML文档解析器 const parser = new DOMParser(); const svgDoc = parser.parseFromString(svgText, 'image/svg+xml'); // 在外部SVG文档中查找目标元素 const targetElement = svgDoc.getElementById(targetId); if (targetElement) { console.log('外部SVG中的目标元素存在'); } else { console.log('外部SVG中的目标元素不存在'); } }) .catch(error => { console.error('检查失败:', error); });
注意事项
- 外部SVG加载受CORS限制,如果跨域且服务器没配置允许,会无法加载。
- 部分浏览器会缓存外部SVG,测试时可强制刷新清除缓存。
内容的提问来源于stack exchange,提问作者Holzchopf
相关产品推荐
相关产品推荐

