Using jQuery to append a string to a CSS property

My current task involves modifying a series of divs with background images named Look-1.jpg to Look-6.jpg. I am looking to add "-cut" to all of them simultaneously to transform them into Look-6-cut.jpg.

I have two collections of background images and I aim to switch between them based on different screen sizes.

While it can be achieved using CSS, doing so individually for each one is time-consuming. Is there a way to accomplish this efficiently using jQuery?

Thank you.


        <div class="item active" style="background: url('/assets/img/collection/Look-1.jpg') center center no-repeat;">
            <div class="carousel-caption item-caption">
                <h5 class="text-black">200 TC Cotton Percale Duvet Cover</h5>
                <a href="#" class="link-inline">View Product<i class="fa fa-angle-right"></i></a>
            </div>
        </div>
    

Answer №1

$("div").css('background-image',(i,cur)=>cur.replace('.jpg','-cut.jpg'));
$("div").each(function(){
  console.log($(this).css('background-image'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item active" style="background: url('/assets/img/collection/Look-1.jpg') center center no-repeat;"></div>
<div class="item active" style="background: url('/assets/img/collection/Look-2.jpg') center center no-repeat;"></div>
<div class="item active" style="background: url('/assets/img/collection/Look-3.jpg') center center no-repeat;"></div>

Is this solution suitable for your needs? The first line replaces every instance of .jpg with -cut.jpg, while the second line verifies the replacement by displaying the updated values.

Answer №2

let backgroundStyling = $(".item").css("background");
let originalImage = "originalImg.jpg";
let updatedImage = "updatedImg.jpg";
backgroundStyling.replace(originalImage, updatedImage);

$(".item").css("background", backgroundStyling);

Your issue should be resolved now. Have a great day!

Answer №3

After experimenting with placeholder images, I managed to find a solution that should work for your specific example.

https://jsfiddle.net/9jphovq1/3/

$(window).resize(function() {
var width = $(window).width();
if (width < 800) {
$(".item").css({"background": "url('https://placeholder.com/200x200/ff0000/000') center center no-repeat"});
} 
else {
$(".item").css({"background": "url('https://placeholder.com/200x200/000000/fff') center center no-repeat"});
 }
 });

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

Set up counters for a variety of Owl Carousel sliders

I am looking to set up multiple owl carousel sliders, where each slider has a counter to track its position. I want the counters to update independently, but I'm running into issues with them not working correctly. Each slider should display a counte ...

Are background styles complete without incorporating quotations?

Let's say I want to include a background image, my code might look like this: background: url(/images/button_bg.png) repeat-x scroll left bottom #146BAE However, when I check the code in Firebug, it shows: background: url("/images/button_bg.png") r ...

What are some strategies for customizing the appearance of child components within a parent component?

I have a scenario where I am using parent and child components. When I use the HTML in another component, I also apply my CSS. For example, in my parent component: HTML <div class="chips"> <p class="tags">Tag 1</p&g ...

I am having trouble placing the button within the image

Essentially, my goal is to place the button within the image and ensure it remains in its position when transitioning to mobile mode or adjusting window size. This is the desired outcome: https://example.com/image https://example.com/button-image .img ...

JavaScript - incorrect order for compiling

Is the user already in my SQLite database? If the user exists: return 500 (ERROR!!) If the user does not exist: return 200 (OK) This is my Node.js + Express script running on the server side. app.post('/adduser', function(req, res){ db.se ...

Bootstrap card elements are failing to display properly, deviating from the expected

My Bootstrap cards are displaying strangely. Instead of having a border, white padding, and a white background like the examples I've seen, mine look like plain text without any styling. Here is an image for reference: https://i.stack.imgur.com/9MsP ...

Using jQuery to locate and delete multiple attributes from div elements

My goal is to locate all div elements with the class name "comment-like" that also have data-id attributes set to 118603,1234,1234,118601,118597. If a div contains any of these data values, then I want to remove that data attribute. I've attempted th ...

Utilizing scrapy and python to gather information on attractions from Tripadvisor

Struggling to extract the names and addresses of attractions from TripAdvisor using web scraping. The suspicion is that there might be an issue with how product.css(...) is written (possibly related to jsons?). Seeking guidance on correcting the code in o ...

Creating a CSS3 Grid Layout with a Fixed Header

I'm having some trouble creating a layout using CSS Grid. My goal is to make the header element 'sticky', so that it remains fixed at the top of the viewport while other content scrolls up and underneath it. Additionally, I want to add a bac ...

Change hyperlink text color on Android CheckBox

I am having a CheckBox with two links embedded in the text. The text is set using the following code: String htmlText = "Accept <a href='someUrl'>Terms and Conditions</a> and <a href='anotherUrl'>Privacy Policy&l ...

I need to extract information from the database and save all entries from the form in order to send them to myself. This includes calculating the real-time multiplication of weight and pieces

For a project, I need to gather contact data from the client, and then populate a MySQL database with the information to create new rows in a table. There's an additional requirement where I have to calculate the total weight of element pieces multip ...

Issues with utilizing jQuery AJAX for form submissions

I am currently customizing a webpage to fit the specific requirements of a client using a template. The page contains two contact forms which are being validated and sent to a PHP file via AJAX. One of the forms is standard, while the other one has been mo ...

Inject an HTML or jade webpage into a div within another HTML or jade webpage

I'm facing an issue in my Node.js project with a script (JS) that is responsible for loading a Jade page into a div of another Jade page using $("#div").load(directory). Despite specifying the directory of the jade page to be loaded, I keep getting an ...

The input box refuses to accept any typed characters

I encountered a strange issue where the input box in the HTML was not allowing me to type anything. const para = document.createElement('p') const innerCard = document.getElementsByClassName('attach') for(let i = 0; i < innerCard.l ...

Implementing external JavaScript files such as Bootstrap and jQuery into a ReactJS application

Just diving into ReactJs, I've got static files like bootstrap.min.js, jquery.min.js, and more in my assets folder. Trying to incorporate them into my ReactJs App but running into issues. Added the code below to my index.html file, however it's ...

Unable to retrieve the value of ng-model using $scope

Having some trouble getting the ng-model value when clicking a button that triggers a function to add each ng-model value to an object. Interestingly, when trying to get the value of $scope.shipNameFirst, it shows up as undefined in the second example. I& ...

tips for displaying a label and text side by side on a single line

Is there a way to keep my label and text on the same line by adjusting the CSS? I've tried using float based on suggestions from other posts, but they still end up on different lines. .indentColumn { width: 71px; padding-top: 5%; } .labelColumn ...

Exploring numerical elements in interactive content

Struggling with the Wikipedia API and encountering issues with the results that are returned. {"query":{ "pages":{ "48636":{ "pageid":48636, Concerned about how to access a specific ID (such as 48636) without knowing it in advance ...

Issue with Rails Controller not Refreshing Page Following Ajax Request

After creating an authentication method to act as a before filter for other controller methods, I've encountered an issue. My goal is to have the method redirect to the root path if the user is not logged in. Below is the code for my authenticate_user ...

Using Local Storage to store arrays in JavaScript/jQuery

Currently, I am implementing a set of multiple buttons each containing data-id and data-name Below is my concept along with some sample code for reference: $(".clickCompare").click(function ({ var id = $(this).attr('data-id'); var ...