Guide on retrieving inline style that has been overridden by CSS using JavaScript

<div style="background: url(http://www.example.com/image.jpg) center center/cover;">

This specific background image defined inline is being replaced by a rule in an external stylesheet:

div {
  background-image: none !important;
}

Here's my query: with JavaScript/jQuery, what method can I use to retrieve the URL of the background image that was initially set in the inline styling but later overridden by CSS?

Note: Attempts to utilize .css() prove unsuccessful since it only captures the computed background style, which in this case is none

Answer №1

If you're open to utilizing Regex :

let foundUrl = $('div').attr('style').match(/url\(["|']?(.+)["|']?\)/);
let url = foundUrl ? foundUrl[1] : 'default.jpg';

Here's the breakdown :

["|']? allows for optional quotes. (.+) captures the URL.

In the second line, we verify if there is a match and assign either the captured URL or a default URL.

Answer №2

You can extract the background image URL using this method:

function getBackgroundImageURL() {
  styles = $("div").attr("style");
  styles = styles.split(";");
  for (i = 0; i < styles.length; i++) {
    styles[i] = styles[i].replace(new RegExp(/http(.*)\:\/\//), "http$1___//");
    styles[i] = styles[i].split(":");
    styles[i][1] = styles[i][1].replace(/___/g, ":");
    if (styles[i][0].trim().indexOf("background") === 0)
      return styles[i][1].replace(/^(.*)url|[\(\)]/g, '').split(" ", 1)[0];
  }
}

Snippet to Test Function

$(function () {
  alert($("div").css("background-image"));
  alert(getBackgroundImageURL());
});

function getBackgroundImageURL() {
  styles = $("div").attr("style");
  styles = styles.split(";");
  for (i = 0; i < styles.length; i++) {
    styles[i] = styles[i].replace(new RegExp(/http(.*):\/\//), "http$1___//");
    styles[i] = styles[i].split(":");
    styles[i][1] = styles[i][1].replace(/___/g, ":");
    if (styles[i][0].trim().indexOf("background") === 0)
      return styles[i][1].replace(/^(.*)url|[\(\)]/g, '').split(" ", 1)[0];
  }
}
div {
  background-image: none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div style="background: url(http://www.example.com/image.jpg) center center/cover;">

Note: The

$('div').css('background-image');
will always return the computed value of none.

Answer №3

Try using the jQuery css function to retrieve the background-image of a specific DIV element:

var divBackground = jQuery('div').css('background-image');

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

The function 'ChartModule' cannot be called, as function calls are not supported

I am encountering a similar problem as discussed in Angular 2 - AOT - Calling function 'ChartModule', function calls not supported ERROR: Error encountered while resolving symbol values statically. Trying to call function 'ChartModule&apos ...

Updating the value of a global variable through dependency injection in AngularJS

One thing I consistently do is inject app.constant('DOCUMENT_ID', window.documentId || 1); into services, controllers, and directives. I'm now looking to convert DOCUMENT_ID into a global variable. The goal is for any changes made to DOCUME ...

Creating a 10-digit unique value can be achieved with either meteor or JavaScript

I am in need of generating 10 character unique codes, containing both letters and digits, to be utilized for system generated gift vouchers. Currently, the code I am using includes 13 numbers. var today = new Date(); Number(today); Is there a different m ...

How can I reduce the delay in Angular 5 to a minimum?

The following code represents a simple request function: getItem() { return this.http .post<ItemModel>(`${this.apiUrl}/${methodUrl}`, {}) .subscribe(response => { ... }); } Depending on the duration of the ...

Expanding circle with CSS borders on all edges

My goal is to create a background reveal effect using JavaScript by increasing the percentage. The effect should start from the center and expand outwards in all directions. Issue: The percentage increase currently affects only the bottom and not the top ...

Uncovering the enum object value by passing a key in typescript/javascript

How can I retrieve the value of an enum object by passing the key in typescript? The switch case method works, but what if the enum object is too long? Is there a better way to achieve this? export enum AllGroup = { 'GROUP_AUS': 'A' &a ...

Troubleshooting a navigation issue in Angular involving the mat-sidenav element of material UI while transitioning between components

I would greatly appreciate your assistance in resolving the issue I am facing. I have been trying to navigate from one view to another, but when I use an <a> tag nested within a <mat-sidenav>, I encounter the following error: "Uncaught (in prom ...

Navigate through an image by panning or scrolling within a div container

I have a container div with an image inside. <div id="container"> <img id="image" src ....> </div> I also have a function that retrieves the image by its ID and applies zoom using styles like this: image.style.transform = `scale(${v ...

Reorganizing the order of Bootstrap columns in a single row for mobile devices

I am struggling with changing the order of Bootstrap columns on smaller devices. I need them to remain in a single row on all screen sizes, but I want them to display in a different order on phones. Specifically, I want the layout to look like this on desk ...

What is the most effective method for attaching text to an element without being affected by the spacing of other div elements

Seeking a method to add text after a textbox in-line, without being pushed to a new line by surrounding divs. The aim is for the text to remain close to the textbox, unaffected by wrapper div boundaries but still relative in position. Any viable solutions ...

Obtaining the mouse position in JavaScript in relation to the website, preferably without relying on jQuery

I came across this code snippet on Ajaxian, but I am having trouble using cursor.y (or cursor.x) as a variable. When I call the function with it that way, it doesn't seem to work. Could there be a syntax issue or something else causing the problem? f ...

Sending form submission data with useFormik via React Router's Link component is a common task in web development. By

My goal is to transfer form data generated through the useFormik and yup hooks to another component using React Router DOM's 'Link' feature. However, I have encountered two issues in this process. Issue 1: I am struggling to pass the useFor ...

Restricting JSON output using date and time values within the JSON object

Currently, I'm in the process of creating a play data reporting tool specifically designed for a radio station. The main concept involves retrieving play history from the playout software's API and manually adding tracks that were played outside ...

Banner with video background (not taking up the entire page)

I'm currently working on a website project that involves using a YouTube video as the banner, but I'm facing some challenges in making it work correctly. So far, this is what I have: #video-background { position: absolute; right: 0; top:1 ...

Tips for adding content to a textarea after making manual changes to its existing content

One issue I encountered is with capturing the enter key on an input field and appending it to a textarea. While this works initially, any edits made directly on the textarea seem to disrupt the functionality. How can this be resolved? I have tested this i ...

Generate a single-page PDF document mirroring the content of a website

I'm facing a dilemma. I need to generate a one-page PDF file without any gaps between the pages. Despite trying numerous plugins, add-ons, scripts, and software, all of them produce multiple pages. What I really require is to have all the pages in a s ...

Is it achievable to set a tab value for an HTML form element?

I'm wondering if it's possible to set a tab character as the value for an HTML dropdown list. Here is the code I currently have: <select id="delimiter-select" class="form-control form-control-sm csv-select"> <option value ...

What is the best way to incorporate a mute/unmute button into this automatically playing audio?

Seeking assistance in adding a mute button for the background sound on my website. Can anyone provide guidance on how to achieve this? Below is the HTML code responsible for playing the sound: <audio id="sound" autoplay="autoplay" ...

Learn how to extract data located between two specific tags using Java HtmlUnit

<span> <a></a> Hello <div>A plethora of irrelevant text</div> </span> My goal is to retrieve only the "Hello" from the webpage. While I can use XPath to target the span, calling .getTextContent() also includes the text ...

Resolved navigation bar problems

As a beginner in web development, I am working hard to launch my first website. Today, I have a question for the stack overflow community regarding a fixed navbar issue. The navbar I have created is functioning properly on Chrome, but when it comes to Fire ...