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".
Asked
Active
Viewed 830 times
-1

Hasan
- 11
- 3
-
Use cycle `for {}` or method `foreach()`. – s.kuznetsov Jun 14 '21 at 19:33
-
Does this answer your question? [How to change the style of elements with same class name](https://stackoverflow.com/questions/20946355/how-to-change-the-style-of-elements-with-same-class-name) – s.kuznetsov Jun 14 '21 at 19:35
-
or https://stackoverflow.com/questions/21813122/changing-content-of-class-using-javascript/21813259 – s.kuznetsov Jun 14 '21 at 19:37
3 Answers
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>
I would suggest that you use jquery for this:
$('p.title, title.title').text('Insert your text');

firesnake
- 11
- 1
- 2