-1

Let's say I have multiple elements (for example a title and p tag) that all have the same class="title". How would I make a JS function that changes the text of those elements to the word "example".

Hasan
  • 11
  • 3

3 Answers3

0

You can query all the elements:

let elems = document.querySelectorAll(".title");

Loop and change the text

for (let i = 0; i < elems.length; i++) elems[i].textContent = "Example";
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

You can select all elements of a class by using document.getElementsByClassName which will return an array-like collection. You can then iterate over the collection using a for loop to change the text content of each element.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Michael Cook
  • 86
  • 1
  • 6
0

You could first get all elements of a certain class like shown below and then iterate trough the elements.

let elements = document.getElementsByClassName('test');
for(let i = 0; i < elements.length; i++) {
  let element = elements[i];
  if(element.nodeName.trim().toLowerCase() === 'div') {
    //Do your stuff
  }
}
console.log(elements);
<div class="test"></div>
<div class="test"></div>
<div class="test-2">
  <div class="test another-class">
    <div class="test-3"></div>
  </div>
</div>
You don't have to use toLowerCase but, i prefer this way. Otherwise all the tagNames will be in caps. Also the trim() is not required. I like to include it, if something acts buggy, and inserts unexpected white spaces you if condition might fail.

I would suggest that you use jquery for this:

$('p.title, title.title').text('Insert your text');
firesnake
  • 11
  • 1
  • 2