javascript - 如何计算 HTML 字符串中的所有图像标签?
问题描述
我有一个由所见即所得编辑器生成的 HTML 字符串。我正在为我的项目使用 Angular。
假设我有一些这样的字符串化 HTML:
'<p>Here is some text with an image</p><br><img src="data:base64;{ a base64 string }"/>'
如何在浏览器端解析这个字符串并计算所有<img>
元素?
我是否需要使用正则表达式,或者是否有可以在浏览器端使用的 NPM 包来为我执行此操作?
注意:我不想在浏览器中呈现这个 HTML。我只想计算图像标签以进行验证。
解决方案
With DOMParser, you can create a document from the string and use querySelectorAll
to select and count them:
const str = '<p>Here is some text with an image</p><br><img src="data:base64;{ a base64 string }"/>';
const doc = new DOMParser().parseFromString(str, 'text/html');
const imgs = doc.querySelectorAll('img');
console.log(imgs.length);
推荐阅读
- python - python循环中的变量
- javascript - 我有一个关于显示带有选择 html 标记和 JS 的项目的问题
- python - 在 windows 上的 jupyter lab 中运行时,dash 服务器文件在哪里?
- android - Android - 片段内 BillingClient 的上下文
- amazon-web-services - EMR spark 应用程序中的 java.lang.OutOfMemoryError
- twilio - 控制设备音量 Twilio.Device
- ios - 我们应该使用 UIView 还是 UIViewController 来实现以下功能?
- javascript - 使用 Angular js 从 XLSX 将数据导出到多个表
- flutter - 开始拖动 NestedScrollView 主体时的瞬时跳转
- javascript - 更改所选选项时,选择值不会更改