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

Mouse over the background of an image in jQuery to create a fade-in effect, without affecting any content inside

Currently facing a challenge with jquery. Please take a look at jsfiddle.net/7HXEF/1/. I am trying to create a DIV with a background image that fades in and out when the mouse hovers over it. However, the inner div with a link should not be affected by the ...

The value from the textbox is not being received by the JavaScript and PHP

I'm encountering an issue with my codes where they are not properly passing the value of the verification code from the textbox to JavaScript and then to PHP. I need assistance in resolving this issue. Below is the snippet of code: HTML: /* HTML c ...

Responsive CSS Dropdown Menu - Divided into Two Columns

After searching for solutions in the support resources and experimenting with various techniques, I am struggling to divide this CSS Dropdown menu into two columns. The nav list is long enough that it extends below the fold. Although the menu adapts respo ...

What is the best approach to alter a user's message depending on the form's ID that was used for submission?

I currently have two separate screens that each serve a specific purpose, where only one can be open at any given time. First is the login form: <form action="/Account/Login" id="login-form" class="form" method="post"> <butto ...

Discovering indistinguishable "Feeling Fortunate" inquiries

My goal is to create a program on my website that can compare the top search results for different queries. For instance, I want it to recognize that the top search result for "twelve" and "12" is the same, leading to https://en.wikipedia.org/wiki/12_(numb ...

limit stop choice

I'm working on modifying a script to limit the number of selections that can be made. Specifically, I want it to stop allowing selections once the total selected items reach or exceed 4. http://jsfiddle.net/dw6Hf/51/ $(function() { $(".selectabl ...

The React app hosted on Firebase displays a message saying "please activate JavaScript to run this application"

I created a web app using React that is hosted on Firebase Hosting, with a backend server utilizing Express and Cloud Functions. You can access the website here: The landing, login, and signup pages are functioning properly. However, when trying to acces ...

Using simpleXML to extract HTML code from an XML document

Presented below is content extracted from an xml file: <Cell> <Comment ss:Author="Mark Baker"> <ss:Data xmlns="http://www.w3.org/TR/REC-html40"><B><Font html:Face="Tahoma" html:Size="8" html:Color="#000000">Mark B ...

My mobile website, built using Bootstrap, appears as if it is zoomed

I recently launched a website called dekhbehen.com, where users can download wallpapers and generate memes. One issue I have encountered is that when the site is accessed via smartphone, it appears zoomed out. You can visit the specific URL causing this ...

What is the reason for not using constants for events in the Node.js programming language?

Although I am new to node.js, my programming background is extensive. I have noticed that in tutorials and production code, developers tend to use hard-coded strings rather than constants to identify events. To illustrate this point, I randomly selected a ...

Is it possible to scroll the grid horizontally?

I have a grid that scrolls vertically, with columns adjusting their width automatically. .grid { display: grid; overflow-y: auto; grid-template-columns: repeat(auto-fit, minmax($min-column-width, 1fr)); } Now, I'm attempting to create a horizon ...

I cannot seem to locate the module npm file

Currently, I am in the process of following a Pluralsight tutorial. The instructor instructed to type 'npm install' on the terminal which resulted in the installation of a file named npm module in the specified folder. However, when I attempted t ...

Retrieving information from the controller within the error callback of a jQuery AJAX request in ASP.NET MVC

I've been working with a jQuery ajax script that looks like this: $.ajax({ type: "POST", url: "Main/receive", // the method we are calling contentType: "application/json; charset=utf-8", data: JSON. ...

Deleting a string by utilizing the Ternary operator in JavaScript

How do I remove the [object Object] from my output shown in the console? I'm looking to print the output without the [Object Object]. Is it possible to achieve this using a ternary operation? data:[object Object] text:Data is supplied by Government ...

How can I search across different fields within a single collection using meteor-autocomplete?

I have implemented mizzao/meteor-autcomplete to retrieve matching items from a MongoDB collection based on user input. While I can successfully search for items in one field, I am facing difficulty searching multiple fields within the same collection. My ...

Combining JSON parameter and multipart/form-data file in a single request using Vue.js

Is there a way to send both JSON parameters and multipart/form-data files in a single request using Vue, similar to how Postman does it? I've been looking into how to submit "multipart/form-data" from VueJs. What I need is to include an image file in ...

Applying personalized CSS to an element based on the condition of a child element in the previous sibling element

I am trying to apply styles to a span element only when a child element in a preceding sibling div element is active, which means a radio button has been checked. I am unable to modify the code and can only use CSS for this task. Any ideas on how to achi ...

What is the reason behind having all bindings resolved during each $digest cycle?

Upon placing a breakpoint on a bound function, I discovered that it is being triggered every cycle. This came as a surprise to me as the timer displaying a countdown on the page was updating other properties as well. The demonstration below showcases thre ...

Navigating the battleground between native and HTML5 mobile applications

As an experienced iOS developer with knowledge in Windows Phone and Android, I have observed the increasing popularity of HTML5 web-apps over native apps. This shift towards HTML5 development frustrates me, as a strong argument can be made for native app d ...

Verifying the presence of a popover

Utilizing bootstrap popover in my project, I am encountering an issue where the target variable may not always exist on the page. Currently, I am displaying the popover using the following code snippet - target = $('#' + currentPopoverId.data(& ...