I am a beginner programmer and I am creating a website using the Tutor LMS Pro plugin.
This plugin allows you to create a panel with courses, unfortunately it is not fully translated into my native language. I’m trying to translate individual headers using JavaScript, but for some reason it doesn’t work.
I have previously translated another element that has the same class as the element I am currently trying to translate (tutor-mb-24).
Therefore, both elements are translated in the same way. I thought that if the second element shares the tutor-mb-24 class but also has other classes, the code will only work for it, but it doesn’t work at all and is inferior to the code that only translates the tutor-mb-24 class for the other element.
I don’t really understand the essence of the problem.
Element I’m working with:
<div class="tutor-col-12 tutor-col-md-8 tutor-col-lg-9">
<div class="tutor-dashboard-content">
<div class="tutor-fs-5 tutor-fw-medium tutor-color-black tutor-capitalize-text tutor-mb-24 tutor-dashboard-title"
>
Text I want to change
</div>
</div>
</div>
I tried:
document.getElementsByClassName("tutor-fs-5 tutor-fw-medium tutor-color-black tutor-capitalize-text tutor-mb-24 tutor-dashboard-title").textContent="New Text";
document.addEventListener('DOMContentLoaded', function() {
var x1 = document.getElementsByClassName("tutor-fs-5 tutor-fw-medium tutor-color-black tutor-capitalize-text tutor-mb-24 tutor-dashboard-title");
if (x1.length > 0) {
x1[0].innerHTML = 'New Text';
}
});
2
Answers
use document.querySelector() method
with CSS syntax…
an other way :
There are many ways to do this; add a unique ID => (
id="css-identifier"
) attribute to the HTML if you have the ability. This would be the easiest way.document.querySelector(‘.element’) would give you the first occurrence of a list of elements.
What if you need a different element with-in the list of elements? You can loop over the elements and get the index of that element within the list of elements or array of elements.
You could create a helper function that does this for you and call it, passing the proper parameters needed for the code block within the method.
See further comments in the code snippet