我正在寻找动态功能,该功能可以一次删除诸如“ style” 属性之类的属性,以将多个非子元素同时作为子元素。像下面一样,我有用于向元素添加多个属性的脚本。用相同的方法将属性删除到多个不同的元素,例如removeAttributes(el1,el2,el3,{“ style”});或者您可以编写任何正确方法的脚本。
<script>
function setAttributes(el, options) {
Object.keys(options).forEach(function(attr) {
el.setAttribute(attr, options[attr]);
})
}
setAttributes(img, {
"src": "../images/...",
"title": "image title",
"alt": "text"
});
<script>
答案 0 :(得分:1)
您可以创建一个函数,在其中可以循环使用所有元素并使用Spread syntax,forEach()
和removeAttribute()
删除属性:
function removeAttributes(attr, ...element) {
element.forEach(function(el){
el.removeAttribute(attr);
});
}
var title = document.querySelector('.title');
var el = document.querySelectorAll('img');
var cat = el[0];
var rat = el[1];
removeAttributes('style', title, cat, rat);
<div class="title" style="font-size: 19px; border: 1px solid purple;">Animals</div>
<img class="cat" src="/" alt="cat" style="color:red">
<img class="rat" src="/" alt="rat" style="color:blue">
答案 1 :(得分:1)
尝试将元素作为数组传入,然后将第二个参数作为要删除的属性名称。
这是下面的工作示例。
JavaScript
function removeAttribute(elements, attributeName) {
elements.forEach(element => {
element.removeAttribute(attributeName);
});
}
window.addEventListener('DOMContentLoaded', () => {
const elements = [
document.getElementById('one'),
document.getElementById('two'),
document.getElementById('three')
];
removeAttribute(elements, 'class');
})
HTML
<a id="one" class="one">Link 1</a>
<a id="two" class="two">Link 2</a>
<a id="three" class="three">Link 3</a>
如果检查元素,您将看到它们不再具有class属性。