获取html字符串中指定类目位置下的指定属性

 需求: 有个别后端返回接口直接返回html字符串,或者需要从html字符串中获取指定属性

解题思路:

1. 将html字符串转化为html dom

2. 通过dom方法获取到指定类名下的指定属性

以下是从html中获取指定类目下所有的src属性


// html 字符串
let htmlStr = `
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>测试</title>
</head>

<body>
  <div id="IntroductionModule">
    <div class="detail_info_wrap">
      <img src="https://img11.buyimg.com/n1/jfs/t1/b9d5d5d5d5d5d5d5.jpg" alt="">
      <img src="//img11.buyimg.com/n1/jfs/t1/b9d6d6d6d6d6d6d6.jpg" alt="">
      <img src="https://img11.buyimg.com/n1/jfs/t1/b9d7d7d7d7d7d7d7.jpg" alt="">
    </div>
  </div>
  <div class="detail_info_wrap">
    <img src="https://img11.buyimg.com/n1/jfs/t1/b9d8d8d8d8d8d8d8.jpg" alt="">
    <img src="https://img11.buyimg.com/n1/jfs/t1/b9d9d9d9d9d9d9d9.jpg" alt="">
    <img src="https://img11.buyimg.com/n1/jfs/t1/b9d0d0d0d0d0d0d0.jpg" alt="">
  </div>
</body>
</html>
`

function getImgSrc(htmlStr) {
  // 创建一个 DOMParser 实例  
  const parser = new DOMParser();

  // 解析 HTML 字符串为一个 Document  
  const doc = parser.parseFromString(htmlStr, 'text/html');

  // 获取id为 IntroductionModule 的元素
  const partBoxes = doc.getElementById('IntroductionModule');
  const detailInfoWraps = partBoxes.getElementsByClassName('detail_info_wrap');

  if (detailInfoWraps.length > 0) {
    // 获取当前 detail_info_wrap 下的所有 img 标签
    const images = detailInfoWraps[0].getElementsByTagName('img');

    // 遍历所有 img 标签并获取 src 属性
    const imgSrcs = [];
    for (let j = 0; j < images.length; j++) {
      imgSrcs.push(images[j].src); // 输出 img 的 src 属性
    }
    return imgSrcs.map(item => {  
      // 如果src属性如果以//开头,会自动添加file://前缀,去掉它  
      if (item.startsWith("file:")) {  
        return item.slice(5); // slice(5) 会去掉前5个字符,即 "file:"  
      }
      // 如果字符串不以 "file:" 开头,则返回原字符串  
      return item;  
    });  
  }
  return [];
}

console.log('getImgSrc(html)', getImgSrc(htmlStr));

结果:

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值