如何筛选指定 HTML 标签的所有有效属性的对象键

huangapple go评论64阅读模式
英文:

How to filter object keys for all valid attributes of a specified HTML tag

问题

任何人知道如何从对象中根据 HTML 标签筛选出有效的键/属性吗?

// 假设有一个具有随机键集的对象(其中一些是有效的 HTML 属性键)
const obj = { ... };

// 我正在寻找类似以下的东西:
const validDivAttributesObj = filterValidHTMLAttributes(obj, "div")

// 甚至类似这样的东西
isValidHTMLAttribute("foo", "div") // false
isValidHTMLAttribute("href", "div") // false
isValidHTMLAttribute("class", "div") // true
isValidHTMLAttribute("href", "a") // true

该辅助函数可以接受任何有效的 HTML 标签键作为第二个参数。是否存在某种 JavaScript 库中的类似功能?

英文:

Anybody knows a good way to filter out the valid keys/props from an object given a HTML tag?

// imagine having some object with a random set of keys (some of which are valid HTML attribute keys)
const obj = { ... };

// I am looking for something like the following:
const validDivAttributesObj = filterValidHTMLAttributes(obj, "div")

// or even something like this
isValidHTMLAttribute("foo", "div") // false
isValidHTMLAttribute("href", "div") // false
isValidHTMLAttribute("class", "div") // true
isValidHTMLAttribute("href", "a") // true

That helper function can accept any valid HTML tag key as the second argument. Does anything like this exist in some kind of JS library?

答案1

得分: 1

你可以使用 document.createElement 创建元素,然后使用 in 运算符检查键是否存在。

const specialAttrs = {'class': 'className', 'for': 'htmlFor'};
// 处理一些在JavaScript中具有不同名称的特殊值

function isValidHTMLAttribute(attr, el) {
  return (specialAttrs[attr] ?? attr) in document.createElement(el);
}

console.log(isValidHTMLAttribute("foo", "div")) // false
console.log(isValidHTMLAttribute("href", "div")) // false
console.log(isValidHTMLAttribute("class", "div")) // true
console.log(isValidHTMLAttribute("href", "a")) // true

注意:上述代码段已经进行了翻译,其中包括代码部分。

英文:

You can create the element with document.createElement, then check if the key exists using the in operator.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const specialAttrs = {&#39;class&#39;: &#39;className&#39;, &#39;for&#39;: &#39;htmlFor&#39;}; 
// handle some special values that have different names in JavaScript

function isValidHTMLAttribute(attr, el) {
  return (specialAttrs[attr] ?? attr) in document.createElement(el);
}

console.log(isValidHTMLAttribute(&quot;foo&quot;, &quot;div&quot;)) // false
console.log(isValidHTMLAttribute(&quot;href&quot;, &quot;div&quot;)) // false
console.log(isValidHTMLAttribute(&quot;class&quot;, &quot;div&quot;)) // true
console.log(isValidHTMLAttribute(&quot;href&quot;, &quot;a&quot;)) // true

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月18日 00:08:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75486667.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定