0

Is there any way to access the attributes of all html elements in a certain class or tagName and set an attribute. For example, to access all the attributes of class navT and set attribute align to center? Or to access the attributes of all table tags and set attribute align to center (Possibly without jQuery)? Any help will be appreciated. Thank you.

  • `document.querySelectorAll('.navT').forEach(element => { element.align = "center"; });` - for `` use `querySelectorAll('table')` or `getElementsByTagName('table')`
    – le_m May 21 '17 at 01:14
  • 1
    @JonathanLonowski `forEach` is a fairly recent addition to `NodeList` - see https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach - I still suggest OP to use your proposed array conversion for compatibility with older browsers if desired – le_m May 21 '17 at 01:25
  • Related: [javascript setattribute to multiple element](http://stackoverflow.com/questions/18455353/javascript-setattribute-to-multiple-element) (has answers for both with and without jQuery) – Jonathan Lonowski May 21 '17 at 01:25

1 Answers1

0

It depends on what you're trying to accomplish (as with anything) but probably the most "down and dirty" and simplest way would be to use:

var arr = document.getElementsByClassName("navT");
for (var i = 0; i < arr.length; i++) {
  arr[i].style.textAlign = "center";
}

Depending on what I were doing I would probably prefer to just make a class in my CSS .center {text-align: center;} and add the class to each element. Just put the following in the for loop above: arr[i].classList.add("center");

Hope that helps!