Is it possible to getElementsByClassName with partial name on Vanilla Javascript?
Asked Answered
R

2

6

I need to get all innerText of all elements that partially match a given string.

Heres a snippet of the code:

<span class="18794221455sarasa">Some text</span>

The class always ends with 'sarasa' the numbers are dynamic. I want to run it on a chrome extension that's why I need it to be on plain Javascript

Reeva answered 14/2, 2020 at 20:52 Comment(7)
Does this help? #3339180Dormitory
Get all elements that have a class, then check whether the class matches the pattern in your loop body.Duna
@Amy The question is about a suffix, not prefix.Duna
@Duna The top answer also has "contains the substring". Read past the title.Dormitory
^ for starting with $ for ending withZondra
This one should do the trick: https://mcmap.net/q/1410797/-how-to-getelementbyname-with-a-regexFilippo
Does this answer your question? getElementByName & RegexFilippo
Q
17

No, you can't use getElementsByClassName like that.

But you can use querySelectorAll with a CSS attribute selector:

document.querySelectorAll('[class$="sarasa"]')

will give you a collection of the DOM elements you want.

See an explanation of this selector here

Quinone answered 14/2, 2020 at 20:56 Comment(0)
V
0

you can use:

document.querySelectorAll("[class$=sarasa]")
Vitrine answered 14/2, 2020 at 20:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.