I have a problem. I'm trying to change the .innerHTML of a span that the name changes every time I refresh the page (only some part of that name changes)
So for example I always use this to change the span's innerHTML:
document.getElementsByClassName('something')[0].innerHTML='new text';
but the problem is that the site now adds random characters after that "something", for example:
<span >some text</span>
and the question is, is this possible to find this span and change the innerHTML of it just by looking for the first part of the class name which is "something"?
CodePudding user response:
Maybe you can use partial selector:
$('[class^="value"]') <-- starts with string
$('[class$="value"]') <-- ends with string
// using jQuery
$('[class^="something"]')[0].innerHTML='new text';
// using document
document.querySelectorAll('[class^="something"]')[1].innerHTML='new other text';
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span >some text</span>
<span >some other text</span>
CodePudding user response:
Can you just add an ID to the spans you want to update? Then just search by those IDs? That's likely the correct way to do it. Otherwise, you might have to write your own thing that loops through the collection of spans in the document and check the class to see if it starts with "something" (prehaps indexOf === 0).
function GetSomethingSpans() {
const AllSpans = document.getElementsByTagName('span');
const AllSpanCount = AllSpans.length;
const SomethingSpans = [];
for (var i = 0; i < AllSpanCount; i ) {
if (AllSpans[i].className.indexOf("something") === 0) {
SomethingSpans.push(AllSpans[i]);
}
}
return SomethingSpans;
}
This is entirely untested, and there might be bugs. But hopefully it's a useful starting point. Could probably adjust it to have a parameter that is the class you're looking for, and you don't have to make it be the first class... hopefully this gets you going.
CodePudding user response:
document.querySelectorAll("something")
will retrieve all elements that have that class, regardless of what others classes are added to the element.