jake
jake

Reputation: 136

function to remove attributes for multiple different elements(which are not child elements) in plain JavaScript

I am looking for dynamic function which can remove something like "style" attribute to multiples different elements at a time which are not child elements. Like below I have script for adding multiple attributes to element. Same way removing attribute to multiple different elements like removeAttributes(el1, el2, el3, { "style" }); or you can write any script which is right way to do.

<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>

Upvotes: 0

Views: 937

Answers (2)

Olawale Akinseye
Olawale Akinseye

Reputation: 177

Try passing the elements in as an array and then the second arguments as the attribute name you want to remove.

Here is a working example below.

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>

If you inspect the elements, you will see they no longer have the class attribute.

Upvotes: 2

Mamun
Mamun

Reputation: 68933

You can create a function in which you can loop through all the elements and remove the attribute by using Spread syntax, forEach() and 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">

Upvotes: 2

Related Questions