To achieve this, you can utilize a combination of querySelectorAll
and attribute selectors. Use the syntax [attr*=value]
.
The attribute selector syntax works as follows:
Selects elements with an attribute name of attr
containing at least one occurrence of value
in the string.
Combining the above solution will look like this:
document.querySelectorAll("[class*='ad']");
This code snippet retrieves all elements whose classes contain ad. You can then iterate over them using a loop or array helper like Array#forEach
. Keep in mind that the result is an HTMLCollection, so convert it into an array before using array methods or use a traditional for
loop.
Here's how the final code should appear:
const ads = document.querySelectorAll("[class*='ad']");
Array.from(ads).forEach(el => {
console.log(el);
})
<iframe class="container"></iframe>
<a class="adp"></a>
<a class="adleft"></a>
<a class="some-other-class"></a>
NOTE: Remember to properly open and close HTML tags, including iframe
. It is not considered a self-closing tag and may lead to invalid HTML markup if not correctly formatted.