0

i can't able to use add classlist function in javascript.. this is my html code

 <div class="container">
 <h1><i class="fa fa-archway">  DJ Party!</i></a></h1>
 <h2>Get the party feel <i class="fa fa-air-freshener">  
 Anywhere,Anytime</i></h2>

this is my javascript code

 var h2=document.getElementsByTagName("h2");
 h2.classList.add("font");

and this is my css code

 .font
  {
  font-size: 500px;
 padding:   400px;
 }
  • 2
    Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Luca Kiebel Aug 27 '18 at 15:34
  • where is ?? only is visible in code... Also please upload full javascript code...as what you expect is not clear .. – Dr Manish Lataa-Manohar Joshi Aug 27 '18 at 15:35
  • 1
    The problem is, that `h2` is not a single element, rather a collection of elements of size one, you need to access the first element of that collection to access it's classlist – Luca Kiebel Aug 27 '18 at 15:35

2 Answers2

3

getElementsByTagName returns a collection. Pass the index to target the element

var h2 = document.getElementsByTagName("h2")[0];
h2.classList.add("font");
.font {
  font-size: 100px;
  padding: 10px;
}
<div class="container">
  <h1><i class="fa fa-archway">DJ Party!</i></h1>
  <h2>Get the party feel <i class="fa fa-air-freshener">  
 Anywhere,Anytime</i></h2>
brk
  • 48,835
  • 10
  • 56
  • 78
2

As @brk mentioned in their answer, getElementsByTagName returns a collection. If you need to, you can also loop through that entire collection to change each element you find.

In this example, this would be useful if you had more than one <h2> element that you needed to change. However, if you know that you will only ever have one element, @brk's answer will work just fine.

var h2 = document.getElementsByTagName("h2");

for (var key in h2) {
    var element = h2[key];
    if (element.classList !== undefined) element.classList.add("font");
}
.font {
  font-size: 100px;
  padding: 10px;
}
<div class="container">
  <h1><i class="fa fa-archway">DJ Party!</i></h1>
  <h2>Get the party feel <i class="fa fa-air-freshener">  
 Anywhere,Anytime</i></h2>
 
 <div class="container">
  <h1><i class="fa fa-archway">DJ Party!</i></h1>
  <h2>Get the party feel <i class="fa fa-air-freshener">  
 Anywhere,Anytime</i></h2>
 
 <div class="container">
  <h1><i class="fa fa-archway">DJ Party!</i></h1>
  <h2>Get the party feel <i class="fa fa-air-freshener">  
 Anywhere,Anytime</i></h2>
Chase Ingebritson
  • 1,559
  • 1
  • 12
  • 25
  • for...in should be avoided for iterating array like object https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript – brk Aug 28 '18 at 03:19
  • @brk My apologies, I was under the impression that that was used. Is `forEach` considered valid in this case? – Chase Ingebritson Aug 28 '18 at 13:52