MARC PLOIT
MARC PLOIT

Reputation: 3

Change innerHTML of span which part of the name changes in time

I'm trying to change the .innerHTML of a span for which 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 my problem is that the site now adds random characters after that "something", for example:

<span class="something RANDOM123 random212312">some text</span>

and my 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"?

Upvotes: 0

Views: 80

Answers (3)

mykaf
mykaf

Reputation: 1390

document.querySelectorAll("something") will retrieve all elements that have that class, regardless of what others classes are added to the element.

Upvotes: 0

Kevin
Kevin

Reputation: 184

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.

Upvotes: 0

Mara Black
Mara Black

Reputation: 1751

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 class="something RANDOM123 random212312">some text</span>
<span class="something RANDOM123 random212312">some other text</span>

Upvotes: 2

Related Questions