Fahad Hasan
Fahad Hasan

Reputation: 10506

change margin-right value of an element using jQuery

I have created a simple <ul> list in HTML and assigned different values of margin-right to each of the <li>'s using CSS (jsFiddle). This is the HTML mark-up of it:

<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;
}

The question which I have in my mind is that would it be possible to replace the margin-right value of the first-child <li> with that of the second-child <li> utilizing the following jQuery snippet:

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

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

Upvotes: 0

Views: 2854

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075567

You're mostly there, you just never asked the second child what its margin-right was:

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

Or more efficiently (and clearly):

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

Or even more clearly:

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

Updated Fiddle - Note that one of the things I had to change in the fiddle was that you had the "No wrap - in head" option chosen, which means that the JavaScript code runs before the elements exist. I changed it to "No wrap - in body" so the script is at the end of the body, so all the elements exist.

Upvotes: 2

Related Questions