英文:
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 = {'class': 'className', 'for': 'htmlFor'};
// 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("foo", "div")) // false
console.log(isValidHTMLAttribute("href", "div")) // false
console.log(isValidHTMLAttribute("class", "div")) // true
console.log(isValidHTMLAttribute("href", "a")) // true
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论