How to use a jQuery each loop to retrieve the margin of an element

I currently have 7 different elements, each with unique margin-left and margin-top properties set in the CSS file. I am looking to loop through these elements and gather information about their margins.

This is what my jQuery code looks like so far:

var $elements = $(".elements");
var elementsMargins = [];
$elements.each(function(index){
    var elementObj = {
        elIndex: index,
        elMarginLeft: this.css("margin-left"),
        elMarginTop: this.css("margin-top")
    };

    elementsMargins.push(elementObj);
});

Unfortunately, I am encountering an issue where I am unable to retrieve these values. Can anyone provide advice or suggestions on how to resolve this problem?

Answer №1

When using the css() method in jQuery, it is important to wrap this in jQuery first. The correct syntax would be:

$(this).css("margin-left"),  //and
$(this).css("margin-top")

A recommended approach would be to utilize the map() method. It eliminates the need to specify the index, as it automatically matches the index within the array of each object.

var elementsMargin = $('.elements').map(function() {
    return {
        elMarginLeft: $(this).css('margin-left');
        elMarginTop: $(this).css('margin-top');
    };
}).get();

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

The ng-repeat ng-switch combination is not functioning as expected

My data can be simplified to the following in my code: function DemoCtrl($scope) { $scope.myData= [ {text: "blah", other: 3, V: 'caseOne'}, {text: "blah", other: 3, V: 'caseTwo'}, {text: "blah", other: 3, V ...

Is it possible for Javascript to fetch a sound from the server once and then duplicate it across n different objects when loaded multiple times?

Incorporating Javascript into my work is crucial. Here's an example: sound = []; for (var i = 0; i < 20; i ++) sound[i] = new Audio("source.wav"); My concern is whether the sound will be retrieved from the server 20 times, or just once. I a ...

Whenever I create a new JavaScript application, the CSS files do not seem to reflect the most recent changes

My Next.js App is running smoothly on my client when I do npm run build and test it with node server js. However, the issue arises when I move the app to a production server. After executing npm run build on the server, everything seems to work fine except ...

The sluggish performance of my website is being caused by the livereload process that was inserted into my index.hml file, causing it

Recently, I've noticed that this line of code is being inserted dynamically into my index.html file, either through Grunt tasks or directly from the server in Heroku. <script type="text/javascript">document.write('<script src="' + ...

What is the best way to switch focus to the next input using jQuery?

Currently, I am implementing the autocomplete feature using jQuery and everything seems to be functioning properly. The only issue I've encountered is with Internet Explorer (IE) - when a user selects an item from the autocomplete list, the focus does ...

jQuery Files in Conflict

The issue I am facing involves the code below. The first function requires linked js and css, while the second one needs a jQuery and javascript file inherited from base.html. However, there seems to be a conflict in loading these files (possibly because o ...

PHP is used in the while loop, but the output should be displayed using JavaScript

I need help with modifying my code to display individual MySQL results in message boxes using JavaScript. Currently, when I click on a message box, it only shows one result for every button. My goal is to have each button display its own unique message fr ...

Issues with Internet Explorer

I am currently working on an aspx page that displays perfectly in Mozilla Firefox but looks distorted in Internet Explorer. The layout in Mozilla appears like this: <form> some stuff <div class="left"> <div class="right> </form> H ...

Preventing Duplicate Entries in Angular Data Posting

I am currently trying to submit a form to a PHP page that will then return a table of data. The process works perfectly fine if I do not include any parameters in the post request. However, as soon as I try to add parameters for the query, I encounter an n ...

Adaptable Text Title

Is there a way to make text headings responsive? When looking at the example provided here, we can see the heading is "The Swift List". How can I ensure that the words "THE" and "LIST" remain aligned with the edges of the word "SWIFT"? While I have managed ...

Elusive Essence: Mysterious Origins of the

Beginner in the world of Ionic and Angular. I am attempting to create a test app and incorporating the factory function. I obtained the design from Ionic Creator and now trying to add my code to it. Here is my controller file. angular.module('app.c ...

What could be causing the HTML layout to break at 769 pixels?

My current project involves creating a simple web page template using HTML/CSS. I followed a tutorial to implement the navigation code. However, at 769px, the layout breaks, causing the page to not be full width and hidden. Here is what happens: Here&ap ...

What is the best approach for creating a single jQuery click function to manage multiple elements within a slider?

Here's my query: I have a slider on my website where each slider item consists of an image and a Bandcamp iframe link. Below is an example code of one of the slider items: <div class="tapecol col-md-4"> <img class="media-ob ...

typescript throwing an unexpected import/export token error

I'm currently exploring TypeScript for the first time and I find myself puzzled by the import/export mechanisms that differ from what I'm used to with ES6. Here is an interface I'm attempting to export in a file named transformedRowInterfac ...

Browsing through tabs to locate specific text

Currently, I am developing a feature for a Chrome extension and I could use some assistance in debugging. The feature involves retrieving a user's input as a string from a text box on popup.html and then scanning through all the open tabs in the curr ...

Expo React Native encountering a network request failure while trying to fetch API and load a local JSON

I am attempting to load a static json file from a local source in my Expo managed application using the following code snippet. useEffect(()=>{ getData()},['']); function getData(){ fetch('../Audio/AudiosObj.json',{'Content-Ty ...

What is the best way to compare a string with a specific object key in order to retrieve the corresponding value?

I'm looking to achieve a relatively simple task, or at least I think so. My goal is to compare the pathname of a page with key-value pairs in an object. For example: if("pathname" === "key"){return value;} That's all there is to it. But I&apos ...

Opening a modal from a different component in Angular 6

I am attempting to launch a modal that is associated with a separate component. However, I encountered an error ERROR TypeError: Cannot read property 'show' of undefined Here is my code: product-catalog.component.html <app-cart-table-modal& ...

What is the method to generate an array of values using a single attribute in GeoJSON data?

Note: After reviewing some possible solutions mentioned in this thread, I found that .map is the perfect fit for what I need, which was not covered in the original post. Thomas's response below addresses my specific requirement. In JavaScript, how ca ...

The functionality of $(selector).css() seems to be malfunctioning

I currently have an html div element stored in a variable var rows = ""; rows += "<div>1111 : Hi there</div>"; Despite multiple attempts, I have failed to add a background color to this div using the following methods: 1. $(rows).css({&apos ...