-3

The first one, I can use document.getElementById to get the object, but on some websites, like the second, there is no id in element, but I also want to get the object with class name and add other class. How can I do this ? And do not use JQuery, Need If one class exist add other class to other element

  if (document.getElementsByClassName('class7') !== null) {
  document.querySelectorAll('class2 class4').className += " classtobeadded";
}
  • `document.getElementsByClassName` _always_ returns an `HTMLCollection` and _never_ `null`. `document.querySelectorAll` returns a `NodeList` which doesn’t have a `className`. – Sebastian Simon Jan 15 '19 at 12:22
  • Possible duplicate of [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Sebastian Simon Jan 15 '19 at 12:22
  • 1
    Possible duplicate of [How to Get Element By Class in JavaScript?](https://stackoverflow.com/questions/3808808/how-to-get-element-by-class-in-javascript) – DBS Jan 15 '19 at 12:23

1 Answers1

4

Assuming you want to select all elements that have class 'class1', and add class 'class2' to them, this will do it:

document.querySelectorAll('.class1').forEach(item => {
    item.classList.add('class2');
});

Note that when using querySelector() or querySelectorAll(), you should use CSS selectors like '.' before a class and '#' before an ID.

Peter
  • 153
  • 1
  • 7
  • Little wrong, i have two separate class, when class number one is in code then add to class two other class number 3. – MoreDeveloper271 Jan 15 '19 at 13:18
  • @MoreDeveloper271 As far as i'm concerned this is exactly what my example does. If you would like to add multiple classes to the selected elements just add them like this: `item.classList.add('class2', 'class3')` and so on. If i'm incorrect, please provide me with your expected DOM output. – Peter Jan 15 '19 at 13:23