Update an element's margin-right value with jQuery

I have designed a basic <ul> list in HTML and applied different margin-right values to each of the <li> elements using CSS (jsFiddle). Here is the HTML code:

<ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
    <li>Fourth</li>
    <li>Fifth</li>
</ul> 

CSS:

ul {
    padding: 0px;
    margin: 0px;
}

ul li {
     display: inline-block;
}

ul li:first-child {
    margin-right: 10px;
}

ul li:nth-child(2) {
    margin-right: 20px;
}

ul li:nth-child(3) {
    margin-right: 30px;
}

ul li:nth-child(4) {
    margin-right: 40px;
}

ul li:last-child {
    margin-right: 50px;
}

I am wondering if it is possible to change the margin-right value of the first-child <li> to match that of the second-child <li> using the jQuery snippet below:

jQuery('ul li:first-child').css('margin-right', '');

For example, if the first-child <li> has a margin-right of 10px and the second-child <li> has 20px, the jQuery should update the first-child <li> margin-right to 20px.

Answer №1

Almost there! Just make sure to check with the second child about its margin-right:

jQuery('ul li:first-child').css('margin-right', jQuery('ul li:first-child').next().css('margin-right'));

For a more efficient and clearer solution:

var first = jQuery('ul li:first-child');
first.css('margin-right', first.next().css('margin-right'));

Or for even clearer code:

var first = jQuery('ul li:first-child');
var marginRight = first.next().css('margin-right');
first.css('margin-right', marginRight);

Check out the updated Fiddle - Please note that in the fiddle, I had to change the "No wrap - in head" option to "No wrap - in body" to ensure all elements exist before running the JavaScript code.

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

By utilizing the <tr> element, one can enhance the border thickness by 1 pixel

Is it possible to ensure that row selection in a table is consistent in terms of border alignment on both sides? https://i.stack.imgur.com/qmZiQ.png If you have any suggestions or solutions, please share them. Thank you! table { margin: 10px; bord ...

Slideshow box with images aligned perfectly

I have designed a container with images, but my goal is to: either show the images inline or stack them on top of each other, and then be able to navigate through them using jQuery. I attempted absolute positioning on both .box and .box img, as well as u ...

Tips for enabling custom tags in the tinyMce editor

<textarea><div style="margin-top: 15px;"> <div class="dropdown "> <p> hello my name is <Enter Your Name> </p> <p> hehe</p> </div> </div> ...

Mastering the art of chaining promises in Mongoose

I need help figuring out how to properly chain promises for a "find or create" functionality using mongodb/mongoose. So far, I've attempted the following: userSchema.statics.findByFacebookIdOrCreate = function(facebookId, name, email) { var self = ...

Can someone explain the process of unescaping characters in an API response to me?

I have created an application that leverages AngularJS to pull data from the WP Rest API V2. The response includes escaped characters, like the example below: "excerpt": { "rendered": "<p>When we go shopping, we encounter many different labeling ...

Is it true that nested CSS IDs function correctly in Firefox, but not in IE8?

My HTML is structured like this: <div id="content"> <div id="asection"> <h1>Some Text</h1> </div> </div> The CSS properties I'm using are as follows: h1 { color:#873C62; font-size:32px; line-heigh ...

Can menus in Vue.js be customized differently for various "pages"?

I am new to Vue and facing a challenge with a common component - menu - that needs to be styled differently on the "TOP page" compared to all other "pages". <template> <div> <menu></menu> <transition name="fade" mode="o ...

Accessing data from another domain using JavaScript with Cross-Origin Resource Sharing (

After researching various CORS and JSON request discussions, I find myself puzzled as to why the first script functions correctly while the second one does not. I am eager to enhance my understanding of CORS, Javascript, XMLHTTPRequest2, and AJAX. The fol ...

The appearance of CSS output is noticeably distinct between iPhones and personal computers

My issue is with the development of my website. When I access it on my PC, everything looks fine. However, when I try to visit the site on my iPhone, there is a noticeable difference in the output. The space above the navigation bar appears differently whe ...

Troubleshooting an Ajax request in Google Scripts with a '$' variable bug

I am trying to implement an AJAX Request using the ajax() method. I have created the functions below on scripts.google.com, but encountered the following error: function AjaxCall() { var arr = { City: 'Moscow', Age: 25 }; $.ajax({ u ...

What is the best method for enabling communication between two users when the identification numbers created by socketIO are automatically generated?

Hey there, hope you're doing well. I've been pondering a question that has left me stumped. I recently came across a course that explained how to send a message to a specific user using socketIO.js by utilizing the `to()` method and passing the ...

Making sure that the div elements are stacked vertically once the top div expands in size

I am dealing with a situation where I have two divs that showcase a list of elements for the user to interact with via a search bar. This is followed by a "Done" button to finalize their selection. <div class="dropdown col" id="dropdown-s ...

Using jQuery's $.Deferred in conjunction with the window object's top.postMessage()

I am having trouble understanding how to effectively use $.Deferred. I currently have a situation similar to window.top.postMessage(mystring, myorigin); This works without any issues. I don't need assistance with sending/receiving postMessage What ...

What is the best approach to storing and retrieving special characters ('+<>$") from a textfield into a database using PHP?

I have a form where users can enter a personal message with a subject. The data entered in the textarea is passed to a Javascript/jQuery function, which then sends it to a PHP file for storage in a database. However, I am encountering issues when special c ...

Is there a way to manipulate the icon to reflect the state of only the audio that is currently playing?

Hey there, I've encountered an issue with my code where the icon seems to change for all divs instead of just the one that is playing when a sound is triggered. Any suggestions on how to address this problem? Check out the code here JavaScript Snipp ...

Ways to conceal the current state changes from being displayed in the URL

I've implemented a React form with text fields and radio buttons to store data in the state. The 'Proceed' button triggers an onClick function: handleClick(event){ console.log(this.state); var userID = 1; firebase.database().ref ...

What is the optimal method for transmitting data for a substantially large music playlist via HTTP?

I am currently in the process of developing an online music player. My main challenge lies in retrieving a comprehensive list of songs from the database and transmitting it to the user. The user should have the ability to create playlists on-the-go, hence ...

How to keep a window/tab active without physically staying on that specific tab

Whenever I'm watching a video on a website and switch to another tab, the video stops playing. But when I switch back to the original tab, the video resumes. Is there a trick to prevent the video from stopping? I've already tried using scrollInto ...

Despite implementing the necessary middleware, the CSS file still refuses to load

My CSS files are not loading properly. When I inspect the element (F12) and go to Networks, my CSS file is not visible. I have added the middleware: app.use(express.static(path.join(__dirname, '/public'))); and required the path above it. I ha ...

Assign the Firebase token to the JavaScript cookie value

Can a cookie store a token value? In my setup with js-cookie, Firebase auth/firestore, and Next.js, I am setting my cookie within the handleUser function like this: const handleUser = async (rawUser) => { if (rawUser) { const user = await fo ...