我正在创建一个 DOM 元素数组并选择一个 img 标签,然后是一系列 p 标签,我如何从 img 中获取 p 和 src link 的 innerHTML?
I'm creating an array of DOM elems and am selecting a img tag, then a series of p tags, how can I get innerHTML of the p's and src link from the img?
这就是我创建数组的方式:const textData = Array.from(document.querySelectorAll('.product-image, .product-detail > p'))
数组内容是一个 img 标签,后面跟着一定数量的 p 标签,根据页面上的项目数量,更多的 img 标签后面跟着更多的 p 标签,我想映射或循环元素和根据元素的标签,将其替换为数组中的 innerHTML(对于 p 标签)或其 src link(img 标签)。我怎样才能在节点中实现这一目标?我不知道如何遍历并确定标签类型并执行指定的操作。
您可以使用地图和 tagNAme
textData.map((element) => {
if (element.tagName === 'IMG') return element.src;
if (element.tagName === 'P') return element.innerHTML;
return '';
})
您可以像下面这样映射元素数组:
const textData = Array
.from(document.querySelectorAll('.product-image, .product-detail > p'))
.map(element => {
if (element.tagName === 'IMG') return element.src
if (element.tagName === 'P') return element.innerHTML
return null
})
如果你想过滤数组中的空值:
const textData = Array
.from(document.querySelectorAll('.product-image, .product-detail > p'))
.map(element => {
if (element.tagName === 'IMG') return element.src
if (element.tagName === 'P') return element.innerHTML
return null
})
.filter(item => item !== null)
以上代码示例如下:
就是在当前页面的devtools的console面板外执行:https://whosebug.com/posts/60461491
这就是我创建数组的方式:const textData = Array.from(document.querySelectorAll('.product-image, .product-detail > p'))
数组内容是一个 img 标签,后面跟着一定数量的 p 标签,根据页面上的项目数量,更多的 img 标签后面跟着更多的 p 标签,我想映射或循环元素和根据元素的标签,将其替换为数组中的 innerHTML(对于 p 标签)或其 src link(img 标签)。我怎样才能在节点中实现这一目标?我不知道如何遍历并确定标签类型并执行指定的操作。
您可以使用地图和 tagNAme
textData.map((element) => {
if (element.tagName === 'IMG') return element.src;
if (element.tagName === 'P') return element.innerHTML;
return '';
})
您可以像下面这样映射元素数组:
const textData = Array
.from(document.querySelectorAll('.product-image, .product-detail > p'))
.map(element => {
if (element.tagName === 'IMG') return element.src
if (element.tagName === 'P') return element.innerHTML
return null
})
如果你想过滤数组中的空值:
const textData = Array
.from(document.querySelectorAll('.product-image, .product-detail > p'))
.map(element => {
if (element.tagName === 'IMG') return element.src
if (element.tagName === 'P') return element.innerHTML
return null
})
.filter(item => item !== null)
以上代码示例如下:
就是在当前页面的devtools的console面板外执行:https://whosebug.com/posts/60461491