实现一个方法 getElementsByStyle()
,该方法查找浏览器使用指定样式呈现的 DOM 元素。它类似于 Element.getElementsByClassName()
,但有一些区别:
getElementsByStyle(document.body, 'font-size', '12px')
。Element.getElementsByClassName()
,仅搜索元素参数的后代,而不是元素本身。Element
数组,而不是 Element
的 HTMLCollection
。不要使用 document.querySelectorAll()
,否则会使问题变得微不足道。在实际面试中,您将不允许使用它。
const doc = new DOMParser().parseFromString(`<div><span style="font-size: 12px">Span</span><p style="font-size: 12px">Paragraph</p><blockquote style="font-size: 14px">Blockquote</blockquote></div>`,'text/html',);getElementsByStyle(doc.body, 'font-size', '12px');// [span, p] <-- 这是一个元素数组。
您可能会发现 Window.getComputedStyle()
方法很有用。
实现一个方法 getElementsByStyle()
,该方法查找浏览器使用指定样式呈现的 DOM 元素。它类似于 Element.getElementsByClassName()
,但有一些区别:
getElementsByStyle(document.body, 'font-size', '12px')
。Element.getElementsByClassName()
,仅搜索元素参数的后代,而不是元素本身。Element
数组,而不是 Element
的 HTMLCollection
。不要使用 document.querySelectorAll()
,否则会使问题变得微不足道。在实际面试中,您将不允许使用它。
const doc = new DOMParser().parseFromString(`<div><span style="font-size: 12px">Span</span><p style="font-size: 12px">Paragraph</p><blockquote style="font-size: 14px">Blockquote</blockquote></div>`,'text/html',);getElementsByStyle(doc.body, 'font-size', '12px');// [span, p] <-- 这是一个元素数组。
您可能会发现 Window.getComputedStyle()
方法很有用。
console.log()
语句将显示在此处。