Is it possible to make HTML element attributes immutable?
If I want to make a javascript object's properties immutable, I can use Object methods such as defineProperties()
, defineProperty()
, and freeze()
. My question is, how can I do the same with HTML element attributes?
I've already tried the aforementioned methods, and while they can be used to prevent an element's properties from being set directly (eg elem.id = 'foo';
), as expected, the underlying attributes can still be changed via setAttribute()
.
An answer of "no, it's not possible" would be acceptable, but I haven't come across any definitive statement to that effect yet.
You could use mutation observers to restore the old attribute value.
new MutationObserver(callback)
.observe(elem, {attributes: true, attributeOldValue: true});
function callback(mutations, observer) {
var target = mutations[0].target;
observer.disconnect();
mutations.forEach(function(mutation) {
target.setAttribute(mutation.attributeName, mutation.oldValue);
});
observer.observe(target, {attributes: true, attributeOldValue: true});
}
Thanks to @DoctorDestructo for the suggestions involving observer.disconnect
which are necessary to avoid an infinite loop.
上一篇: junit测试课的多个runwith
下一篇: 是否有可能使HTML元素属性不可变?