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;
}
<div class='sharedclass'>Hi Im A Shared Class 1</div>
<div class='sharedclass'>Hi Im A Shared Class 2</div>
<div class='sharedclass mb-3'>Hi Im A Shared Class 3</div>
<button class='btn btn-primary' onclick='changesecondtext();'>Change Second Item</button>
<button class='btn btn-primary' onclick="changeanytext(0, 'Moo');">Change 1 (0) to Moo</button>
<button class='btn btn-primary' onclick="changeany_text(2, 'Moo Three!');">Change 3 (2) to Moo Three!</button>