Verify whether the document includes a class that closely matches the provided string using Javascript

I need help identifying elements that include the letters 'ad'.

For example:

<iframe class="container" /> <!-- Not relevant -->
<a class="adp" /> <!-- Relevant -->
<a class="adleft" /> <!-- Relevant -->
<a class="some-other-class" /> <!-- Not relevant -->

Would using a forEach method be appropriate for this task? Any assistance would be greatly appreciated.

Answer №1

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.

Answer №2

To target all elements that include the word "ad" in their class attribute, you can utilize an attribute selector. For more information on this topic, refer to this documentation.

document.querySelectorAll('*[class*="ad"]');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing null values within the map function in React JS

I am currently developing an application using React JS. The app displays a list of users along with the status of books (available, taken, or requested) for each user. However, I'm encountering an issue where even after filtering out the books based ...

Navigating through an array and Directing the Path

My array contains objects as shown below: const studentDetails = [ {id:1, name:"Mike", stream:"Science", status:"active"}, {id:2, name:"Kelly", stream:"Commerce", status:"inactive"}, { ...

Dividing one SVG into Multiple SVGs

I'm facing a challenge with loading an SVG overlay on a Google Map. The SVG file is quite large, about 50mb, resulting in a delay of around 10 seconds for it to load in the browser. One solution I'm considering is splitting the SVG into 171 smal ...

I am facing an issue where my Javascript hide and show function is not working properly when clicked. Despite not giving

I am currently working on a Javascript onClick function to toggle the visibility of content in a lengthy table. I initially set part of the table's class to display: "none" and added a button to show the hidden content when clicked. However, nothing i ...

Leveraging nodemailer for automated email delivery

Hey there! I'm looking for some advice on how to set up scheduling with emailing using nodemailer. Ideally, I'd love to be able to schedule emails to send every day at 9am within a web app using nodemailer. However, I'm not sure where to st ...

React Native Child Component State Update Issue

In my code, there is a Child component that triggers a function in the Parent component. However, when the function is triggered, an error related to the setState method is thrown. Issue with Promise Rejection (id: 0): The '_this12.setState' i ...

Using Express.js and Angular for user authentication and session management

In my current project, I am utilizing expressjs and angularjs to create an app. The setup involves expressjs serving a single .html file that houses an angular single-page-application. All routing is handled by angularjs, while expressjs provides web servi ...

Customize your Bootstrap design by selecting a background color that doesn't

Why is the dropdown background black when used in a bg-dark navbar but white when used outside of the navbar? I want to use a white dropdown in a dark navbar. Here is my complete code: MyCode Here is my navbar & dropdown: <nav class="na ...

I've been struggling with my Create React app for the past two days, and it just won

When trying to create a React project using the command `npx create-react-app reactproject`, I encountered an error: npm ERR! code ENOENT npm ERR! syscall spawn C:\Users\SUJITKUMAR\Desktop npm ERR! path D:\WebDev\React npm ERR! ...

Error: The function row.child.hasClass is not a recognized function

My challenge is creating row details for DataTables without using Ajax. I have implemented something like this: $(document).ready(function () { function format ( name, value ) { return '<div>Name: ' + name + '<br /> ...

The tab indicator in Material-UI fails to update when the back button is clicked

My code is currently functioning well: The tab indicator moves according to the URL of my tab. However, there is a peculiar issue that arises when the back button of the browser is pressed - the URL changes but the indicator remains on the same tab as befo ...

Guide to creating a responsive layout using CSS and HTML

I am looking to position the main contents (content 1 and content 2) in between two side menus on my exercise page. At the moment, the main contents are overlapping with the two menus. Can someone guide me on how to fix this alignment issue? Thank you. ...

How can you capture the VIRTUAL keyCode from a form input?

// Binding the keydown event to all input fields of type text within a form. $("form input[type=text]").keydown(function (e) { // Reference to keyCodes... var key = e.which || e.keyCode; // Only allowing numbers, backspace, and tab if((key >= 48 && ke ...

What is the reason for not using constants for events in the Node.js programming language?

Although I am new to node.js, my programming background is extensive. I have noticed that in tutorials and production code, developers tend to use hard-coded strings rather than constants to identify events. To illustrate this point, I randomly selected a ...

Is it possible to create an image or logo that moves in sync with the user's scrolling

Having trouble articulating this question, but I'm trying to replicate the logo in the top right corner of this website: I want the logo to move along with the user as they scroll down, remaining visible at all times. Any ideas on how to achieve this ...

The issue arises in Selenium IDE when a variable is mistakenly identified as a string instead of a

Hey there, I've encountered an issue while using Selenium IDE. I'm trying to increment a variable by two, but instead of performing numerical addition, it seems to be concatenating strings. <tr> <td>store</td> <td> ...

Update: When a variable changes during onUploadProgress in Vue.js, the DOM is not re

Having a bit of an issue here. I'm working on an app where users can upload images using axios. In order to enhance the user experience, I'm trying to implement a loading bar. Here's what it looks like: <div class="loadingbox" :style="{ ...

Uploading images seamlessly through ajax

Despite the abundance of tutorials, I am struggling to make them work. In my input form for file upload, I have: <input onChange="userPreviewImage(this)" type="file" accept="image/*" style="display:none"/> Here is my Javascript code: function use ...

Customize the CSS for MaterialUI's TablePagination's MenuItem

Having trouble figuring out how to override CSS for the child component MenuItem within TablePagination? Check out this link for more information: https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/TablePagination/TablePagination.j ...

"None of the AJAX callbacks are triggered, neither success nor error functions are being executed

document.getElementById('myform').addEventListener('submit', function (e) { // avoid the default action of the submit e.preventDefault(); $(function () { var artist = document.getElementById("artist"); var rows = document.getEl ...