get element by class name with javascript and change it function

You may have seen the get element by id in javascript, which is great when there is only one element but what if you need to get the element using its class name

The issue with classes is that they can be re-used so may not be unique.

Using the following code will return an array of the class elements that it finds, and then you can access them like an array or javascript object.

HTML

<div class='shared_class'>Hi Im A Shared Class 1</div>
<div class='shared_class'>Hi Im A Shared Class 2</div>
<div class='shared_class mb-3'>Hi Im A Shared Class 3</div>
<button class='btn btn-primary' onclick='change_second_text();'>Change Second Item</button>
<button class='btn btn-primary' onclick="change_any_text(0, 'Moo');">Change 1 (0) to Moo</button>
<button class='btn btn-primary' onclick="change_any_text(2, 'Moo Three!');">Change 3 (2) to Moo Three!</button>

Javascript

// here is a basic version
function change_second_text() {
  var shared = document.getElementsByClassName("shared_class")[1].innerHTML = "<b>Yay i changed...</b>";
}

// here is a function with some more options
// this one you can pass in the item number and the text replace it with on the function
function change_any_text(item_num, text) {
  var shared = document.getElementsByClassName("shared_class")[item_num].innerHTML = text;
}
Hi Im A Shared Class 1
Hi Im A Shared Class 2
Hi Im A Shared Class 3

Other Items in javascript
Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

❤👩‍💻🕹

Random Quote
Most people can do absolutely awe-inspiring things,” he said. “Sometimes they just need a little nudge.
Unknown