Retrieve the background-image URL from a div element using Javascript

Currently, I am faced with an element on a website that has the following structure:

<div id="item" style="background-image: url('url to the image')"></div>

I am now in need of a JavaScript solution that can extract only the URL of this background-image and substitute it with a URL stored in a variable.

Is there a neat way to achieve this? :)

Answer №1

To access the specified id of a div element, you can utilize the document.getElementById method and then use setAttribute to update the style attribute with a string that includes the updated URL stored in yourVar. Here's an example:

var section = document.getElementById('section');
var newBackground = 'background-image: url(' + yourVar + ');';
section.setAttribute('style', newBackground);

Answer №2

Update the background image of element with id 'item' using variable var.

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

Text font automatically adjusts size in Chrome on Android

It seems that when a paragraph of text reaches a certain length, Google Chrome on Android decides to resize the text and make it larger (which can cause some interesting results). I've noticed that on my website, about half of the p-tags stick to the ...

The function Router.use is looking for a middleware function, but instead received an object in node.js /

I encountered an issue while trying to setup routing in my application. Whenever I attempt to initialize a route using app.use() from my routes directory, I receive an error stating that Router.use() requires a middleware function but received an Object in ...

What is the best way to retrieve AJAX responses from JSON data that contains multiple sets of information

["12-Feb-2017","06-Feb-2017","5","45","40","Neha shishodia","USD","unit2","phase1","Change Request","Client Approval Awaited"]["07-Feb-2017","04-Feb-2017","6","54","48","Neha shishodia","USD","unit2","phase1","Change Request","Manager Approval Awaited"] T ...

Mobile devices seem to be constantly refreshing website images

I have a landing page consisting of multiple sections with images as the background, each section occupying the full screen. In one specific section, the images change every 5 seconds. The website works smoothly on desktop, but I encounter issues on mobil ...

Eliminate table styling within PHP

Is there a simple method to strip out inline styles and attributes from a table using PHP. For instance, how can I remove class, style, width, and height from the following code: <tr class=xl96 height=30 style='mso-height-source:userset;height:23 ...

Adding HTML components to an image with adjustable dimensions

A graphic designer has provided us with an image featuring three selection boxes. I implemented the necessary HTML elements and CSS to display three overlapped selection boxes on top of the image, using pixel values for positioning. However, the original ...

Which specific file name patterns does npm publish consistently exclude?

When using the npm publish command, the documentation mentions that certain files will not be included in the package unless explicitly added to the "files" list in package.json or un-ignored with a specific rule. What exactly are these "certain patterns"? ...

What is the best way to conceal a button before printing and have it reappear once the printing process is finished?

I have a button on my webpage with the id "print_req" that is used to trigger a JavaScript function for printing the page. I want this button to be hidden during the printing process and then reappear afterwards, so it does not show up in the printed docum ...

internet explorer 11 not properly aligning text to center

I've encountered an issue with center-aligning a canvas and overlapping image on different browsers. While Chrome and Firefox display it correctly, Internet Explorer does not cooperate. The canvas is not centered, but the image is. I've tried var ...

Retrieve a collection of items based on their data-id attribute

I need to create a list of label elements with data-id attributes. I will use the values from these labels to set images on the main container. The function changeimage is returning a nodelist with null elements, but I am not sure why this is happening. ...

Stopping errors are a common occurrence in synchronous AJAX

I recently encountered an issue with my AJAX request setup. In the success callback function, I called a new function to render Google links and made another AJAX call. To address some performance concerns, I attempted to change these asynchronous calls t ...

Discovering the Perfect Cube Using Factorization Technique

Looking for some guidance on a C/JS program to find perfect cubes using the factorization method below. Any assistance is greatly appreciated. 3 * 3 * 3 3 * 3 * 3 3 * 3 * 3 JavaScript Code var num=19683; var arr=[]; for(i=2;i<num;i++){ if(nu ...

Creating a dynamic menu layout using CSS

I've experimented with various methods to create a fluid menu, but none have been successful. Currently, I have an interactive menu that sometimes displays 6 items and other times 7 items. When I have 7 items, the menu aligns perfectly across the wid ...

Difficulty arranging objects in both horizontal and vertical orientation within a single flexbox container

I'm struggling with aligning my bootstrap flexbox container properly. I want the image to remain horizontal on the left, while the title, description, and "powered by" sections stack vertically to its right. So far, all my attempts to achieve this hav ...

Mathjax2 in React is not supported in React v17

After successfully running recat-matcjax2 on react 16, I encountered some issues when updating to react version 17. I am facing two specific errors: These are the error files: https://i.sstatic.net/iy0ZV.png https://i.sstatic.net/trfrL.png Here is my ...

Ways to generate an element with a specific identifier using a single line of code

When creating an element, I often use the following syntax: var foo = document.createElement('div'); To set the ID of the div, I would typically do this: foo.setAttribute('id', 'divName'); After some searching online, I ca ...

Encountered a problem while attempting to create a new Angular project due to an unexpected termination of JSON input during parsing

Angular CLI: 10.0.4 Node: 12.18.3 npm : 6.14.6 Whenever I attempt to start a new angular project, I encounter errors that prevent the process from completing successfully. The installation of packages hangs indefinitely and eventually throws an erro ...

What is the best way to ensure that each box in the Tabs panel is colored when it is selected?

Can someone show me how to make the individual tab bars light up or change color when selected? I am not sure how to do it. Thanks in advance! import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Pape ...

Is it possible for CSS to prevent the insertion of spaces?

When filling out a form, I am able to insert spaces in inputs but not in the textarea (which is necessary). Interestingly, inserting spaces in the textarea works flawlessly. <form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="mu ...

Guide to switching between 3 classes with mouseover using JavaScript

Currently, I am dealing with an unordered list that contains 4 items. The goal is to have the list grow to 100% of its width when hovered over, while all 'noun hovered li' items should shrink to a width of 0%. Once the cursor leaves, everything s ...