Exploring the DOM using querySelector()

Is there a way to extract the url value from the inline style of this particular div?

<div 
class="w-18 h-18 sm:w-20 sm:h-20 bg-gray-200 mx-auto bg-center bg-cover border border-gray-400 rounded-ch" 
style="background-image: URL('https://d14u0p1qkech25.cloudfront.net/club_8702_65d827dd-03b9-4cce-8876-8bd33f306460_thumbnail_250x250')"
></div>

I managed to select the div element using

document.querySelector('.rounded-ca')

However, when I accessed the .style property on the div, it returned an object with only the following key:

{ "0": "background-image" }

Any suggestions on how I can retrieve the actual url value that is associated with the background-image property?

Answer №1

Consider trying out this approach:

let targetDiv = document.getElementsByClassName("rounded-ch")[0]
let styleAttribute = targetDiv.getAttribute("style")
let imageUrl = styleAttribute.replace("URL('", "").slice(0, -2)
console.log(imageUrl)
<div 
class="w-18 h-18 sm:w-20 sm:h-20 bg-gray-200 mx-auto bg-center bg-cover border border-gray-400 rounded-ch" 
style="background-image: URL('https://d14u0p1qkech25.cloudfront.net/club_8702_65d827dd-03b9-4cce-8876-8bd33f306460_thumbnail_250x250')"
></div>

Answer №2

To retrieve the style attribute from the selected element, I employed the method .getAttribute() on the chosen node as demonstrated below:

document.querySelector('rounded-class').getAttribute('style')

Answer №3

The `style` attribute of the div element contains properties that were previously mentioned. To access each style property, such as `background-image`, you can do so by accessing its camelCased counterpart. For instance: `style.backgroundImage`.

You can then scan the string for the content located between the `url(""` and `")` characters.

const div = document.querySelector('.rounded-ch');
const { backgroundImage } = div.style;
const pattern = /(?<=url\(").*(?="\))/g;
const [url] = backgroundImage.match(pattern);
console.log(url);
<div 
class="w-18 h-18 sm:w-20 sm:h-20 bg-gray-200 mx-auto bg-center bg-cover border border-gray-400 rounded-ch" 
style="background-image: URL('https://d14u0p1qkech25.cloudfront.net/club_8702_65d827dd-03b9-4cce-8876-8bd33f306460_thumbnail_250x250')"
></div>

Answer №4

Explore the details on getComputedStyle method:

let targetElement = document.querySelector('rounded-ca');
let computedStyles = window.getComputedStyle(targetElement);
console.log(computedStyles.getPropertyValue('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

Implement lazy loading for scripts in Next JS

Currently working on a project with Next JS and focusing on optimizations through Google's Page Speed Insights tool. One major performance issue identified is the presence of 3rd party scripts, specifically the Google Tag script (which includes Google ...

Organize an array of objects in JavaScript into a structure with nested children

I am facing a challenge with organizing an array of objects based on parentId and sort values. I need to create a nested array with 'children' and ensure proper sorting. Consider the following data: [{ id: 1, sort: 2, parentId: null ...

How can I incorporate a custom font into my Git Pages website?

Having trouble adding an external font to my GitHub page. The font is in my directory, but I can't seem to get it to work on the page at https://github.com/Aadesh9985/Aadesh9985.github.io I've attempted various methods without success... I came ...

Is there a way to access the parent element within the javascript function of an asp:CustomValidator?

Is there a way to access the parent element in the asp:CustomValidator JavaScript function in order to verify if the associated checkbox has been selected? For instance: I'm faced with this code: <tr> <th class="gray ...

What is the best way to mention a user within a response to a command using Discord.js?

How can I get my bot to ping users? https://i.sstatic.net/mbY0h.png I want my bot to notify users when it responds to a command, similar to how I'm responding in the image with @ON, without actually mentioning them in the message. I attempted to se ...

What is the JavaScript method for updating an HTML5 datalist to show new options?

When populating options dynamically into an HTML5 datalist, I'm facing an issue where the browser tries to display the datalist before all the options have loaded. As a result, the list either does not show up completely or only partially shows up. Is ...

Retrieve every potential option of a dropdown menu

One of my tasks involves working with a select field that has various values: africa europe america asia oceania Whenever a value is selected, I aim to apply a specific CSS class to a particular div, with the name of the CSS class matching the selected v ...

jQuery simple authentication is not functioning as expected

I am encountering an issue with making a CORS request to a server that uses basic authentication. I am using jQuery version 1.5.1 and have the following code snippet: $.ajax({ type: 'GET', global: true, url: theSource, crossDomai ...

Website navigation toolbar with access level control

I'm currently working on a website with various webpage links in the navigation menu, and I want to restrict access for non-admin users. Would it be better to set up different access levels or just use passwords on each page? What approach would be mo ...

Using Preloaded Images as Textures in THREE.js: A Step-by-Step Guide

This specific project includes a fallback routine for non-canvas, using a preloading method for images. Although the images are added and loaded correctly, I am facing an issue with integrating them into THREE.js as it tends to reload the images using its ...

Tips for ensuring the Google Maps API script has loaded before executing a custom directive on the homepage of an Angular website

Issue - I am facing issues with Google Maps autocomplete drop-down not working on my website's main page even after parsing and loading the Google Maps API script. The problem seems to be a race condition on the main page of my website, specifically i ...

ASP.net bundling causing issues with script rendering and display

I recently encountered an issue with external scripts on one of my views. To resolve it, I copied and pasted each function from the URL into a new local js script, bundled them together, and everything was displaying correctly. However, when I tried to use ...

Securing the Integrity of My JavaScript Code

As we all know, JavaScript EDIT can function as a client-side scripting language, meaning it runs on the client side for certain operations. This is especially true when using Node.js (which I currently am). I'm currently working on an app and utiliz ...

Creating a dropdown list with a pre-selected item in HTML is a simple task

I have two items in a dropdown menu, and I only want the data for the selected item to appear. Is there a way to make one item's data appear by default? HTML code: <div class="box-header"> <div class="dropdown" align="left"> ...

Interact with the screen by moving your mouse or sw

I am absolutely intrigued by this captivating visual effect. My goal is to implement this on an iPhone or iPad using touchmove functionality. Is there anyone out there who can assist me with this task? Here is the JavaScript code snippet: $(document).bin ...

Sometimes the AngularJS scope is refreshed only intermittently

I am encountering an issue with a list of cards retrieved from an API and displayed in a table using ng-repeat. The problem arises when I attempt to delete a card - sometimes it remains in the view, while other times it disappears as expected after confirm ...

Display only alphabetic characters in the text field

I have a jQuery function that I am working on: $('#contact_name').on('input', function() { var input=$(this); var re =/^[A-Za-z]+$/; var is_email=re.test(input.val()); if(is_email) { } else { } }); This function is targeted at the fol ...

Can you please tell me the event that is triggered when an option is unselected in Vue.Drag

I am trying to figure out the event for selecting an item since I already know about the "choose" event. However, I am uncertain about what to use for un-selecting an item. In my particular case, I am unable to utilize the @end event. <draggable :list= ...

Ionic Vue Modal displays duplicated content

Trying to implement a modal in an Ionic Vue app, I encountered a strange issue where the content is being displayed twice. This problem persists even when using the example code provided on the Ionic website: The modal content component looks like this: & ...

Displaying items using the flex property can cause the top resize feature to be unreachable

My issue revolves around the display of input errors, which are causing the top section to become inaccessible. I am looking for a solution that will align the content both vertically and horizontally in the center. The challenge arises when the card conta ...