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
Page Views

This page has been viewed 183 times.

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
You want to be the best, you MUST put the long yards in! Nothing comes easy in life so stop wishing and start DOING! So many people would rather bitch and moan than help themselves. Dont be one of those negative drainers, start today, make a small change and keep going forwards with this attitude!
Unknown