Reputation: 568
Setting an attribute on DOM element may throw an exception if the name is invalid. The docummentation at https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute mentions the exception that gets thrown:
InvalidCharacterError The specified attribute name contains one or more characters which are not valid in attribute names.
How can I check (in Javascript, or JSX) if an HTML attribute name is valid or not? I would like to do a simple check on the string before setting the attribute at all, so I can abort before this error occurs.
Upvotes: 1
Views: 980
Reputation: 456
const isValidAttribute => (attr) {
const unacceptableAttributes = [
//Anything you dont want added here
]
//make this false to prevent adding javascript events
const allowEvents = true;
//testing if it is a valid attribute
const el = document.createElement("div")
let answer = false;
try {
element.setAttribute(attr)
answer = true
} catch (e) {}
el.remove;
if (!answer ||
!allowEvents && attr.startsWith("on") ||
unacceptableAttributes.indexOf(attr) !== -1) {
return false
}
return true;
}
Upvotes: 0
Reputation: 182
var element = document.getElementById("myElement");
try{
//attribute name is invalid so it will throw an error
element.setAttribute("", "value");
}
catch(error){
console.log("Invalid Attribute Name");
}
<h1 id="myElement"></h1>
Upvotes: 1
Reputation: 675
const validAttrs = ['class', 'style'] // add the ones you want
function isValidAttr (attrName) {
return validAttrs.indexOf(attrName) !== -1
}
isValidAttr('class') // true
isValidAttr('div') // false
Upvotes: 0