Using jQuery to add a class to an image element when the source attribute contains a specific

I have a bunch of text that looks like this

<div id="justThisDIV"><p>Some paragraph <img src="http://mydomain.com/image.jpg"/> </p>
<p><img src="http://mydomain.com/wow.png"/></p>
<p><img src="http://notmydomain.com/blah.png"/> Wow this is boring</p></div>

Is there a way to assign a class to all images from my domain, meaning those with the URL mydomain.com within the DIV having the ID justThisDIV

I attempted the following without success

<script type="text/javascript">
    $(document).ready(function() {
        $("div#justThisDIV img[src*=mydomain.com]").addClass("full-width");

    });
</script>

Thank you

Answer №1

ANSWER REVISED ONCE MORE

To achieve the desired result, incorporate the 'attribute contains' selector and utilize the .parent().attr('id') method along with a conditional statement to append it to the specific div.

$("img[src*='imgur']").each(function () {
    if($(this).parent().attr('id')  == "thisDiv") { $(this).addClass('mine')}
});

Alternatively, if you prefer adding the class to the container instead, simply adjust the reference as shown below:

$("img[src*='imgur']").each(function () {
    if($(this).parent().attr('id')  == "thisDiv") { $(this).parent().addClass('mine')}
});

DEMO - Apply a class to the image DEMO 2 - Assign a class to the image's container

Answer №2

Look no further, this is the solution you've been searching for

$('img')
    .filter(function() {
        return this.src.match(/^http:\/\/mydomain.com/);
    })
   .addClass("full-width");

Check out the demonstration on jsfiddle: http://jsfiddle.net/9ZABC/

Answer №3

If you want to experiment with selecting attributes that start with a specific value, here's an example for you to try out:
Example:

$( "div[data-start^='example']" ).addClass('highlight');

For more information on this topic, check out: http://api.jquery.com/attribute-starts-with-selector/

Answer №4

A good practice is to avoid triggering functions on DOM elements that may not be present. It's important to first check if they exist before taking any action.

var $img = $('img[src*="mydomain.com"]');

// Check if at least one image you need exists
if ($img.length) {
    $img.each(function() {
        // Add custom class to each img tag
        $(this).addClass('my_class');
    });
}

While it is possible to add the class directly with the following line:

$('img[src*="mydomain.com"]').addClass('my_class');

I believe it's better to:

  1. verify the existence of the elements
  2. keep the code clear and easy to understand
  3. make the code easily adaptable for potential future operations on the images

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

An AJAX event handling function returns a null value upon invocation

Recently, I've been working on a function named 'getAuthor' which includes an AJAX event. Here's the code snippet: function getAuthor(id){ $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){ ...

Looking for a different method to remove a list item within an unordered list using CSS instead of HTML

I am currently working on designing a mock-up website using CSS codes. If you want to see the mock-up website, you can visit: Here is the specific list I am referring to: This is the expected outcome: In order to achieve the desired result, I used HTML ...

Can a horizontal navigation bar be designed to span the full width of the page without relying on a table?

I'm trying to create a horizontal navigation menu with variable width buttons that spans the full width of the containing div. I was successful in achieving this by using a table, as demonstrated in this example. The table cells adjust their size base ...

SheetJS is experiencing difficulties parsing dates correctly

Need help exporting an HTML table to an Excel file using the SheetJS library. Here's my code snippet: var table = document.getElementById("tableToExport"); var ws = XLSX.utils.table_to_sheet(table, { sheet: "Raport Odorizare", da ...

What is the best way to style a tooltip in an ASP.NET application using CSS?

protected void grd_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { foreach (TableCell cell in e.Row.Cells) { ...

Is it possible to retrieve JavaScript object properties using HTML elements?

I have fetched an array of objects using jQuery.getJSON(). Each object should be represented by an HTML div element, allowing users to click on the element and access all properties of the corresponding object. What is the most efficient approach for achie ...

What are some ways I can customize the appearance of a Bootstrap 5 Navbar specifically when it is in the collapsed

Currently utilizing Bootstrap 5, my goal is to align the Navbar social icons to the left when the navbar is collapsed for small/mobile devices, and to the right when viewed on a larger screen. Can you assist in identifying which selectors need styling for ...

Invokeing JQ's on() function to trigger a click event on a concealed Google Infobox.Js

I'm currently using the Infobox.js plugin from Google API V3 to show custom info windows. However, I've encountered an issue where the infobox.js code hides each marker's info window and brings it to the front using z-index. Is there a way ...

What causes an Undefined array key error when using AJAX POST?

I am having trouble passing a text string to a PHP Variable using AJAX. Every time the POST request is sent, I see this error message: Warning: Undefined array key "mydata" Although the alert displays the correct value, the PHP page shows the ...

The issue with EJS Header and Footer not showing up on the

I am currently building a basic todo list application using EJS. However, I am encountering an issue when running it. I would like to run app.js with the header and footer in EJS, but it seems that it is not recognizing the header despite using what I beli ...

Is there a way to trigger a function after a tooltip or popover is generated using Twitter Bootstrap?

Is there a way to manipulate a tooltip or popover with twitter bootstrap after it has been created? It seems like there isn't a built-in method for this. $('#selector').popover({ placement: 'bottom' }); For instance, what if I ...

Show button image beyond the limits of the hyperlink

Is it possible to create a button with a background image that changes on hover and when active, while also having the active state display an image that extends beyond the anchor's bounds? Check out my sprite here: The top half of the sprite represe ...

A simple guide on how to surround every incorrect input index in mapped inputs with red borders

I am incorporating a modal that corresponds each element of the object newCompanies to a specific row: {newCompanies.map((company, index) => { return ( <div> <div className="side- ...

My current objective is to extract the information from a specific item within a combobox by implementing the following code

alert($("select[name="+this.name+"] option:selected").text()); However, I am not receiving any output unless I explicitly specify the name of the combobox instead of using this.name. This issue may be related to the way quotes are being handled. ...

Automatic switching between Bootstrap 5 tab panes at precise time intervals

Is there a way to have the Bootstrap 5 tab-pane automatically switch between tabs at set intervals, similar to a Carousel? I found a code snippet on this link, but it appears to be outdated and only works for Bootstrap 3. Could someone assist me in updati ...

CSS Tricks: Placing a Panel Just Off the Page Edge

Having difficulty adjusting a panel slightly off the page like this: click here for image Attempted using width: 120% While it does work, resizing causes the image to move from its original position. I want it to remain consistent on different screens. ...

Galaxy S5 browsers experiencing issues with website responsiveness

I've been using jquery to dynamically remove a div in order to change the appearance of my home screen on smaller devices. It's been successful on my Macbook Air and Iphone X, but unfortunately, it doesn't seem to work properly on Android de ...

Splitting a list of accordions into two columns with CSS and React - a step-by-step guide!

I am looking for a way to showcase a list of Accordions in a two-column layout. Each Accordion consists of both a Summary and Details section, with the Details being visible only when the Summary is clicked. Unfortunately, I won't delve into the imple ...

What could be causing my divs to overlap?

I recently started coding and I'm facing an issue with my <header> and <section> divs overlapping each other. I was under the impression that being block elements, <section> should be displayed below <header>. Any suggestions o ...

Utilizing static HTML, CSS, and JavaScript for secure backend administrative control

Seeking a solution for my static html, CSS, and JS website which includes some Jquery elements. I want to implement a user-friendly backend system that allows non-developer admins to log in, easily edit sections or change images with their own preferences. ...