Utilize jQuery to retrieve data attributes and set them as CSS properties in a key-value format

Looking at the HTML below:

    <h4 data-padding-top="100" data-padding-left="0" data-text-align="left" data-color="#ffffff">Promotion Two</h4>

I aim to use the data attributes as CSS styles for the H4 element. I have attempted to achieve this with the JS code provided, but the css function call is producing an error (I prefer not to insert style=""; directly in the HTML as per client's request):

    var H4obj = {},
        $thisH4;

    function css(el, styles) {
        console.log(styles);
        for (var property in styles)
            el.style[property] = styles[property];
    }

    $('h4').each(function(index, el) {
        $thisH4 = $(this);

        var el = $thisH4;

        data = $thisH4.data();

        $.each(data, function(key, val){
            H4obj['data-' + key] = val;
        });

        $.each(H4obj, function(index, value){                
            css($thisH4, {index:value});
        });
    }); 

Could there be a simpler approach to achieve this? Your assistance would be greatly appreciated.

Answer №1

It seems like there are a few errors in your code. You might have more variables than needed and since you're already using jquery, it's best to utilize jquery's built-in method .css.

$('h4').each(function(index, el) {
    var $el = $(el); // the jquery h4 object

    var data = $el.data();
    $el.css(data);
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h4 data-text-align="left" data-color='red'>Test One</h4>

<h4 data-text-align="right" data-color="blue">Test Two</h4>

In essence, .css necessitates key-value pairs with the "data-" removed from the keys. This is exactly what .data() provides. Ensure all variables are declared properly (they may have been declared above the snippet you posted, though it's not clear).

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

Disable the scroll animation feature for certain IDs

I implemented JavaScript code to animate scrolling for each block with a specific ID. However, when I added Bootstrap's tabs, the animation interfered with the functionality of the tabs. Is there a way to disable the scroll animation specifically for ...

Hide Details tag only on mobile view

How can I easily close the default opened <details> tag on mobile? I am working with Wordpress. Any suggestions on how to achieve this? <details open> <summary>Details</summary> Something small enough to go unnoticed. </ ...

Using jQuery to add a class and define a variable when clicked on

In order to achieve the functionality of changing the class of a link to active while removing the active class from other links, and setting a variable value based on the clicked link, you can refer to the code below. When "1" is clicked, the variable fir ...

Disregard IDs when linting CSS in ATOM

Is there a way to configure csslint in Atom to exclude "ids" and prevent the warning "Don't use IDs in selectors" from appearing? Update: Despite my question being flagged as potentially duplicate, I delved deeper in my own research and ultimately fo ...

How to perfectly position multiple tables using CSS

I am relatively new to the world of HTML and CSS. I have successfully created several tables, but now I am struggling to display them all on a single line within a designated box. Despite my best efforts, I have not been able to achieve the desired result. ...

Two interactive dropdown menus featuring custom data attributes, each influencing the options available in the other

Looking to create interactive select boxes based on the data attribute values? This is the code I currently have: HTML <select id="hours" onchange="giveSelection()"> <option value="somethingA" data-option="1">optionA</option> <o ...

The div element is persisting despite AJAX attempts to remove it

I am currently developing an application that allows users to post and comment. I have a situation where I need to delete a specific comment by clicking on the associated 'x' button. To achieve this, I am making an Ajax call to the remove-comme ...

Revamp Password Security with PHP, Ajax, and JQuery

Working on creating a form to update a user's password. No errors in console but the data isn't updating. The validation part is functioning, so the issue might lie with the Ajax implementation? Note: I am aware of not using mysql in PHP long-te ...

CSS Style for Organizing Content

I'm struggling to create CSS for a hierarchical display, resembling a tree structure of files and folders. Currently, I am using nested unordered lists in my HTML: <ul> <li>animals<ul> <li>dogs</li> <li>c ...

The preventDefault() function is not functioning properly on the <a> tag

As a JavaScript beginner, I decided to create an accordion menu using JavaScript. Although I was successful in implementing it, I encountered a bug in my program. In this scenario, uppercase letters represent first-level menus while lowercase letters repr ...

Adjusting element position while scrolling

Objective The goal is to have the page navigation display lower on the page by default. This will provide a cleaner layout as shown in the image below. Context An interactive element for navigation was implemented utilizing Headroom.js. This library d ...

What steps can I take to reset my JavaScript code once its original purpose has been fulfilled?

I created this code, learning as I went along. It measures Beats Per Minute as one clicks the left-mouse-button each time they feel a pulse. After 10 clicks, the JavaScript code takes all the values in the array and calculates an average BPM. The issue ar ...

Tips for adding information during a follow-up ajax request

I am facing an issue with my Ajax calls. The first one works fine and displays data, but the second one is not returning anything. I have already attempted to append the data to different elements, but I still get no results displayed. $(function () { ...

Leverage and repurpose OOP objects

I am exploring how to inherit from Button using prototypes. Despite my efforts, the alerted name remains "Sarah" as it is the last Child created. I believe the Creator Class should be responsible for setting the name using a Method in Button. Check out m ...

The final item in the Bootstrap carousel will automatically conceal the right control option

Currently utilizing bootstrap 4.0, I am seeking a solution to hide the left control on the first item and hide the right control on the last item within the carousel. I believe jQuery can assist in achieving this. The left control should be hidden at all ...

I am unable to utilize folder paths in CSS within my React application

Having trouble setting a background image in CSS within my React app. When styling and setting the image from a React component, it works just fine. Can anyone provide assistance? This code snippet will work: const style={ width:'300px', ...

How can I best access the object being exposed on the webpage using <script type="text/json" id="myJSON">?

In our current project, we are successfully using AMD modules to organize and structure our code. One idea I have is to create an AMD module that accesses a script tag using a jQuery ID selector and then parses the content into JSON format. Here's an ...

Issue with Mjpg paparazzo.js functionality not functioning as expected

I am currently exploring alternative methods to view my security cameras without relying on browser support for mjpg streaming. I have come across Paparazzo.js, which appears to be a promising solution that I want to experiment with: https://github.com/rod ...

How can I show a Spinner component overlay in a TextField, replacing the usual iconProps rendering the icon in Fluent UI?

I am looking for a way to conditionally display the Spinner component in the exact location where an icon would normally appear if passed to iconProps in TextField. I have managed to implement conditional rendering of the icon and spinner, but incorporat ...

Dynamic content loading for Twitter Bootstrap Popover using Ajax

Below is my code for dynamic content loading in a popover using AJAX. The popover displays correctly after the initial load, but there is an issue with its behavior on the first "show" event – it appears and disappears immediately. $("a.mypopover"). ...