Obtain precise Inline CSS formatting and Style designation

Is there a way to extract specific inline CSS styles from an element, capturing both the style name and its value?

Consider an element with various inline styles like this:

<div style="background-color:red; display:block; background-size:cover; background-attachment:fixed; background-repeat:repeat-y; cursor:pointer; width:100%"></div>

My goal is to retrieve the element's styles (including both the style name and value), focusing only on those related to "background" while disregarding others like "display, cursor, width," and so forth.

To achieve this using jQuery, one might execute the following code snippet:

$("div").attr("style");

This approach returns all of the element's styles, including undesired ones. Ideally, I am seeking a solution that delivers output similar to the following, filtering out non-"background" related styles:

background-color:red; background-size:cover; background-attachment:fixed; background-repeat:repeat-y;

While it is possible to access individual styles like so:

$("div").css("background");
$("div").css("background-size");

The limitation lies in obtaining just the style values without discerning between different variations such as "background-image" or "background-repeat-x/y."

Answer №1

Using string manipulation for this task is not recommended, and it's surprising to see other answers relying on it. The style element is the more appropriate tool for handling inline styles.

To access all inline styles, you can simply inspect element.style. This object displays each inline CSS rule separately, as shown in the image below:

https://i.sstatic.net/BJBEF.png

The object provides a clear list of rules that can be accessed individually (for instance, element.style[0] represents background-color). It also includes a dictionary for accessing specific rules by name, allowing for easy filtering to find desired rules.


A live demo demonstrates how to extract rules containing the term background from the object (check the console). The results are organized into an array of name and value pairs for convenient access:

var el = document.getElementById("thediv");

var result = [];

for (var i = 0; i < el.style.length; i++) {
    if (el.style[i].indexOf("background") !== -1) {
        result.push({name: el.style[i], value: el.style[el.style[i]]});
    }
}

console.log(result);
<div id="thediv" style="background-color:red; display:block; background-size:cover; background-attachment:fixed; background-repeat:repeat-y; cursor:pointer; width:100%"></div>

Answer №2

If you want to extract background styles from div elements in jQuery, you can use the following code:

$('div').each(function() {

style_arr=$(this).attr("style").split(';');
for(i=0;i<style_arr.length;i++) {
    if(style_arr[i].indexOf('background')!=-1) {
        console.log(style_arr[i]);
    }
}

});

Check out a live demo here: http://jsfiddle.net/sx3psqvh/

Answer №3

Here is a possible solution:

$(document).ready(function(){
    var selectedBackgroundStyles = $.grep($("div").attr("style").split(';'), function(style) {
        return style.indexOf("background") > -1;
    });
    console.log(selectedBackgroundStyles);
});

http://jsfiddle.net/8sk2tnj4/

Answer №4

One possible way to achieve this is by following these steps:

let styleAttribute = $("div").attr("style");
let arrayOfStyles = styleAttribute.split(';');
let backgroundAttributes = '';
for (let j = 0; j < arrayOfStyles.length; ++j) {
    if (arrayOfStyles[j].includes("background")) {
        backgroundAttributes += arrayOfStyles[j] + ';';
    }
}   
console.log(backgroundAttributes);

To begin, extract the entire style attribute, then separate all CSS attributes by ";" into an array. Next, iterate through each element in the array to search for values containing "background". If found, append that value to a variable with ';' attached at the end of each one.

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

Ways to optimize angular performance by minimizing unnecessary data binding:NSUTF8B

When comparing the performance of rendering a list using Angular versus other libraries like Handlebars, I noticed about a 10x decrease in speed. In my case, the table does not need to update dynamically when the model changes. If necessary, I can simply ...

When a <dl> element is nested within an <ol>, it will be rendered as a list format

I'm facing an issue with my CSS that affects how different browsers render definition lists embedded within ordered lists. In IE10, the list displays as expected - a bulleted list inside the ordered list without affecting the numbering. However, Firef ...

How to swap content by dragging and dropping using Container JS or JQuery

In possession of ten containers, here is an illustrative scenario: if I drag the first container and drop it onto the eighth container, a replacement occurs transforming eight into one. 1st container is dragged and dropped onto the 8th container triggerin ...

Extract website information, transform into JSON format, input into SQL database?

I have this interesting project where I am seeking to extract data from an external webpage, transform it into a specific structure, and then store it in a database. The purpose of doing this is purely for enjoyment - I'm essentially replicating an e ...

The 'this' variable is malfunctioning when trying to assign a JSONP array to an AngularJS controller

I'm working with a REST service in my angular controller and using JSONP to make the call. I need to store the array that is returned from the service into a variable. This is what I currently have: this.testTheRest = function() { $http.jsonp(&a ...

The Gatsby node encounters an error while trying to create a new page

I am currently working on creating sub-pages for a projects category in Gatsby. The parent page for each project is generating correctly, but the sub-pages are not behaving as expected. Each project has the potential to have zero or multiple sub-pages, an ...

An alert must be displayed before executing any jQuery function

On my website, I have implemented click functions that toggle the class of specific elements when clicked. Here is an example of the code: $(".phenomenology_toggle_box").click(function() { pageClicked = '.phenomenology_toggle_box'; escCl ...

Enhancing my website with automated slider functionality

I currently have an image slider on my website that includes a hover effect. You can view the code here: http://jsfiddle.net/Nctfa/. Here is the HTML code: <div class="accordian"> <ul> <li> <div class="image_title"> ...

Screening data entries

.js "rpsCommonWord": [ { "addressWeightPct": "60", "charSubstituteWeightPct": "15", "nameWeightPct": "40", "oIdNumber": "21", "shortWordMinLthWeightPct": "100", "substituteWeightPct": "5", ...

Utilizing jQuery callback parameters for interacting with PHP functions via AJAX

I am facing issues with AJAX results when using jQuery. Below are the functions I have defined: <script> function hello(callback, funct, val) { var ret = 0; console.log(val); $.ajax({ type: 'GET', ...

Using React JS and Redux to make an API call prior to accessing any route

Greetings, I am currently working on a single-page application using React and Redux, and I've encountered an issue. In my application, the admin has the ability to open or close the app from the admin panel. If the app is closed by the admin, users ...

What is the process of importing the csv-writer module?

Can we use the import statement instead of const createCSVWriter = require('csv-writer').createObjectCsvWriter; Is there a way to achieve this using import ...

"Creating a 3D effect with inset shadow using three.js

I am looking to add inset shadow to my object using three.js, creating a unique effect similar to this image: https://i.sstatic.net/L8Ori.png Imagine something like a ring with engraved text. ...

Package videojs along with the videojs-ima extension

For a few days now, I have been struggling to create a single JavaScript file that contains all the necessary components to play videos with Google IMA ads. However, I keep encountering errors, particularly player.ads is not function, which seem to be rela ...

Acquiring variables from a JQuery Ajax request while invoking a JavaScript file

I'm currently experimenting with using JQuery Ajax to retrieve a javascript file. I need to pass some parameters to it, but I'm not entirely sure how to do so in Javascript (PHP seems easier for this). Here is my current setup: function getDocum ...

Transform - change the data type of the input from text to number

My issue is that I need Deform to render an input type number in a specific way: <input type="number" name="end" value="" id="deformField4" class=" form-control "> Instead of rendering it as: <input type="text" name="end" value="" id="deformF ...

Unable to locate the reverse for 'my_views_name' without any arguments in Django. Bridging server-side code with client-side JavaScript using jQuery

How can I create a button to update a URL after fetching data from the database using jQuery AJAX? This is my code in views.py: def list_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') data = [] for i in lists: ...

Problem with Internet Explorer version 9 and above and the Flip Card feature

I have a cool feature for one of my clients where clicking on one div causes another div to flip in its place, like a card flipping over. It's kind of like those portfolio image flippers, but instead of images, it flips divs with content inside. How ...

Is there a way to selectively isolate elements based on their class name using Jquery and retrieve the position of their parent element?

I currently have 4 <ul> elements in my HTML page, each of them containing child <li> elements. Whenever a user clicks on one of the <li> elements, I dynamically add the active class name to it. Additionally, I want to display an icon in a ...

Removing directory that begins with a period in Node programming

When attempting to use node to delete a folder that starts with a period, such as ".TestDir," I encountered an issue. Despite my expectation that the following code should work: await fs.promises.rm('.TestDir', { recursive: true, force: t ...