styling multiple elements using javascript

Recently, I created a jQuery library for managing spacing (margin and padding).

Now, I am looking to convert this library to pure JavaScript with your assistance :)

Below is the JavaScript code snippet:

// Useful Variables
let dataAttr = "[data-m], [data-mt], [data-mr], [data-mb], [data-ml], [data-my], [data-mx], [data-p], [data-pt], [data-pr], [data-pb], [data-pl], [data-py], [data-px]";
let dataSpacing = $("[data-spacing]").find(dataAttr);
let p = "px";

// Margin
const marginSpacing = () => {
  dataSpacing.each(function() {
    $(this).css({
      'margin': $(this).attr("data-m") + p,
      'margin-top': $(this).attr("data-mt") + p,
      'margin-right': $(this).attr("data-mr") + p,
      'margin-bottom': $(this).attr("data-mb") + p,
      'margin-left': $(this).attr("data-ml") + p,
    });
  });
};marginSpacing()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body data-spacing>
  <p data-mt="20">Text</p>
  <p data-mr="20">Text</p>
  <p data-mb="20">Text</p>
  <p data-ml="20">Text</p>
</body>

Answer №1

Here is the code snippet:

const dataAttributes = "[data-m], [data-mt], [data-mr], [data-mb], [data-ml], [data-my], [data-mx], [data-p], [data-pt], [data-pr], [data-pb], [data-pl], [data-py], [data-px]";
let dataSpacingValues = [...document.querySelectorAll('[data-spacing]')].map(element => element.querySelectorAll(dataAttributes));

dataSpacingValues.forEach(dataSpacingDataElements => {
  dataSpacingDataElements.forEach(item => {
    item.style.margin = item.dataset.m;
    item.style.marginTop = item.dataset.mt;
    item.style.marginRight = item.dataset.mr;
    item.style.marginBottom = item.dataset.mb;
    item.style.marginLeft = item.dataset.ml;
  })
})

Answer №2

Thank you to "connexo" for providing the solution that fixed the issue.

I have made some adjustments to the code to better fit my needs.

Below is an updated version of the code:

let dataAttr = "[data-m], [data-mt], [data-mr], [data-mb], [data-ml], [data-my], [data-mx], [data-p], [data-pt], [data-pr], [data-pb], [data-pl], [data-py], [data-px]";
let dataSpacing = [...document.querySelectorAll('[data-spacing]')].map(el => el.querySelectorAll(dataAttr));
let p = "px";

dataSpacing.forEach(dataSpacingDataEls => {
  dataSpacingDataEls.forEach(el => {
    el.style.margin = el.dataset.m + p;
    el.style.marginTop = el.dataset.mt + p;
    el.style.marginRight = el.dataset.mr + p;
    el.style.marginBottom = el.dataset.mb + p;
    el.style.marginLeft = el.dataset.ml + p;
  })
})

Hats off to @connexo for the help!

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

"Utilize Angular's $http module to execute a POST request for

Hey everyone, I'm a beginner with AngularJS and I've run into a problem while working on my project. I encountered this error: ReferenceError: $http is not defined when attempting to utilize the following code: 'use strict'; ...

Rotating the transform causes the div to be pushed beyond the screen boundaries and renders

html, body { margin: 0; padding: 0; overflow-x: hidden; } /*HEADER*/ #header { background: blue; background-attachment: fixed; background-size: cover; width: 100vw; height: 100vh; } .btn-1, .btn-2, .btn-3 { background ...

Why does this vow continue to linger unresolved?

I've been experimenting with a code that involves adding promises to a queue for processing in a non-blocking manner. One code snippet behaves as anticipated while the other doesn't, leaving me puzzled. Problematic Code: const axios = require(&a ...

Incorporate validation features within a jQuery method

I am struggling with some HTML and jQuery code that generates links based on user input. HTML <input type="text" id="text" placeholder="Enter text" autofocus /> <a id="link1" class="btn btn-info" href="#" target="_blank"> Search 1 </a> ...

Running multiple npm scripts on both Unix and Windows systems can be achieved by using the "npm

Is there a way for me to execute multiple npm scripts synchronously, one after another? Below are the npm scripts I have in my project, which includes both bower and npm packages: { "scripts": { "installnpm": "npm i", "installbower": "bower i", ...

Stop material button from animating when clicked

On my webpage, I have created a unique button structure using Angular Material design: <button mat-button class="library-tile-button"> <button mat-button class="edit-library-button"> <img class="edit-library-img" src="..."/> ...

Clicking on the menu to reveal the dropdown options using JavaScript

I have created a drop-down menu for my website, but I am facing an issue. When I click on the links again, it does not work properly because I lack expertise in JavaScript. I would appreciate any help and suggestions from all of you. Thank you for your tim ...

What are the steps to integrate TypeScript into JavaScript code?

How can I import a TypeScript class in a Node CommonJS JavaScript file? When using mongoose in my TypeScript code, I typically do the following: // user.model.ts export const UserModel = model<User>('User', schema); In my JavaScript code: ...

How can we reset multiple selected values (mui chips) in a React Material-UI Autocomplete field when changing the value in a different field?

Is there a way to clear the mui-chips in Material UI Autocomplete TextField when the value in another field is changed? I have been struggling with clearing the subtype value when the Type value changes. Although I can update the drop-down options based on ...

Using a combination of HTML and CSS3, craft this specific geometric design

Here's a sample image demonstrating how to create this button using CSS3. I would greatly appreciate any assistance! ...

Detecting Android devices

Issue: My website functions properly on desktop but has a problem with the carousel images skewing on iPhones. To address this, I created a separate CSS styling for iPhone devices and used a JavaScript function found online to detect iPhones and iPads. Un ...

Creating a unique look for unordered list items in a dropdown navigation

I'm currently working on creating a drop-down menu using nested unordered lists. The functionality of the menu is all set, but I'm running into some styling issues. The main link that triggers the drop-down should have a blue background with whit ...

Developing a Typescript module, the dependent module is searching for an import within the local directory but encounters an issue - the module cannot be found and

After creating and publishing a Typescript package, I encountered an issue where the dependent module was not being imported from the expected location. Instead of searching in node_modules, it was looking in the current folder and failing to locate the mo ...

Upload the image data into the input file tag

Is there a way to take a string code stored in a JavaScript variable that is retrieved from the Cropit plugin (used for cropping images) and then set this information into an input file tag? I want to be able to send it via AJAX to PHP. Here is the JavaSc ...

Transmit the identifier of the span tag to the URL seamlessly without the need to refresh

<div id="unique50">Greetings</div> Transfer the code 50 to the designated link by clicking on the specific div element without requiring a page reload ...

Vue Method always executed (regardless of click event)

I'm fairly new to vue and still getting a grasp on the fundamentals of my code. Currently, I am facing an issue with a Method. It should only trigger when the user clicks on the button, but it seems to be triggered all the time. I even tried adding ...

Vue unable to load material icons

The icons npm package "material-icons" version "^0.3.1" has been successfully installed. "material-icons": "^0.3.1" The icons have been imported as shown below. <style lang="sass"> $material-icons-font-path: '~material-icons/iconfont/'; ...

waiting to display information until it is necessary

I am currently working on optimizing my website for improved loading speed and responsiveness. Users can scroll through up to 4k images, apply filters, and sort them based on their preferences. Below is the code snippet for my filtering function: function ...

The sign-up button mysteriously vanishes after the page is refreshed

I am encountering an issue with the sign up button during the user registration process. There is a checkbox for Terms & Conditions, and the button should only become enabled after checking this box. Everything seems to be functioning correctly, but when I ...

Unable to retrieve the API key in Nuxt framework

I am fairly new to NuxtJS and have been following tutorials on it. I am having trouble displaying the {{planet.title}} on my page. However, when I use {{$data}}, I can see all the planets. I want the title of the planet's name that I have in the slug ...