const elements = document.getElementsByClassName('tutor-fs-5');
const secondElementString = "Some other text!"
const thirdElementString = "Change the third elements textContent!"
// helper function, pass in elements, index, string
function changeTextUsingIndex(els, index, str) {
// basic for let loop that iterates over the elements
for (let i = 0; i <= els.length; i++) {
// conditional if index of for loop strict comparision of index of parameter passed in
if (i === index) {
// change the text to passewd in string
els[i].textContent = str;
}
}
}
// call your method and pass in params
// start at 0, second index would be 1 so we pass in 1 as the targeted index
changeTextUsingIndex(elements, 1, secondElementString);
changeTextUsingIndex(elements, 2, thirdElementString);
<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 with same class
</div>
<div class="tutor-fs-5 tutor-fw-medium tutor-color-black tutor-capitalize-text tutor-mb-24 tutor-dashboard-title">
Text with same class
</div>
<div class="tutor-fs-5 tutor-fw-medium tutor-color-black tutor-capitalize-text tutor-mb-24 tutor-dashboard-title">
Text with same class
</div>
</div>
</div>
@PoulBak 嗯,如果他想使用 id,这是一个可以引用元素并且在 DOM 中始终是唯一的属性,他只需将该属性添加到他想要定位的 HTML 中,例如:
. Then in JS or CSS reference that ID to target that specific element. const uniqueID = document.querySelector('#uniqueId') or document.getElementById('uniqueId') See MDN for more info ID Selectors getElementById()