使用原生JavaScript获取图片alt文本并添加至无序列表
原生JS实现两个图片alt文本处理需求
一、获取所有带alt属性的图片,生成包含alt信息的无序列表
核心逻辑是遍历带alt属性的图片,逐个生成列表项,挂载到无序列表后插入DOM。代码示例:
// 获取所有带alt属性的图片元素 const imgsWithAlt = document.querySelectorAll('img[alt]'); // 创建无序列表容器 const altList = document.createElement('ul'); altList.className = 'alt-text-list'; // 可自定义类名用于样式控制 // 遍历每个带alt的图片 imgsWithAlt.forEach(img => { const altText = img.getAttribute('alt'); // 创建列表项 const listItem = document.createElement('li'); // 根据alt内容设置列表项文本 if (altText.trim() === '') { listItem.textContent = '图片为装饰图(alt为空)'; } else { listItem.textContent = `图片ALT文本:${altText}`; } // 将列表项添加到无序列表 altList.appendChild(listItem); }); // 将生成的列表插入到页面末尾(可指定其他容器位置) document.body.appendChild(altList);
关键说明:
- 用
img[alt]选择器精准定位带alt属性的图片,避免选中其他带alt的非图片元素 - 用
forEach遍历元素,写法比索引循环更简洁直观 - 用
textContent设置文本,比innerHTML更安全,避免XSS风险
二、原生JS实现图片后添加提示Div(替代原jQuery代码)
对应原jQuery的逻辑:遍历所有图片,根据alt的状态(无属性、为空、有值)添加不同提示Div,原生JS实现如下:
// 获取页面所有图片 const allImgs = document.querySelectorAll('img'); allImgs.forEach(img => { const altText = img.getAttribute('alt'); let tipDiv; // 分场景处理 if (altText === null) { // 无alt属性的情况 tipDiv = document.createElement('div'); tipDiv.className = 'empty-alt'; tipDiv.textContent = '这张图片缺少ALT属性'; } else if (altText.trim() === '') { // alt为空字符串的情况 tipDiv = document.createElement('div'); tipDiv.className = 'no-alt-text'; tipDiv.textContent = '这张图片是装饰图'; } else { // 有正常alt文本的情况 tipDiv = document.createElement('div'); tipDiv.className = 'show-alt-text'; tipDiv.textContent = `这张图片的ALT文本是:${altText}`; } // 将提示Div插入到图片后方 img.after(tipDiv); });
关键说明:
getAttribute('alt')在元素无该属性时返回null,这是区分“无alt属性”和“alt为空字符串”的核心- 用
img.after()直接在图片后插入元素,对应jQuery的after()方法 - 全程用原生DOM方法创建元素,避免拼接HTML字符串,更安全可控
内容的提问来源于stack exchange,提问作者Laurence L
相关产品推荐
相关产品推荐

