Ewr Xcerq
Ewr Xcerq

Reputation: 192

Changing style of an element via vanilla Javascript

<a href="" style="right:0px">right</a>

I would like to change it into

<a href="" style="left:0px">right</a>

In jQuery I can do this

$('a').attr('style','left:0px');

But how can I do this in traditional javascript without using jquery?

Upvotes: 7

Views: 10968

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219920

var elements = document.getElementsByTagName('a'),
    l = elements.length;

while ( l-- ) elements[l].style.left = '0px';

Here's the fiddle: http://jsfiddle.net/236pk/


If you're using a modern browser, you can use this one liner:

document.querySelectorAll('a').forEach(e => e.style.left = '0px');

Here's the fiddle: http://jsfiddle.net/236pk/24

Upvotes: 6

SpYk3HH
SpYk3HH

Reputation: 22570

JavaScript answer already there, but you tagged it jQuery, while mentioning you didn't want to use jQuery. Maybe you just don't realize how easy JavaScript is with jQuery in play, and it can be used just about anywhere you use JavaScript, with 0 bad side effects. So below is how easy it is to do this with jQuery, and with way less code.

$("a").css({ left: "0px", right: "" })

jsFiddle

I know you showed a jQuery example, but it's not quite right, thus I'm guessing you were thinking it would be easier in JavaScript since you couldn't figure out the jQuery proper way. Just include the right in the style and set its value to an empty string and that will set you style correctly.

And just a little more, while the answer selected shows an easy way to do it, it does not account for what is in your question. Namely the a tag already having style="right:0px;". If you want to make it all correct, use his formula but add one line:

var elements = document.getElementsByTagName('a'),
    l = elements.length;

while ( l-- ) {
    elements[l].style.left = '0px';
    elements[l].style.right= ''; // here in lies the added line, it removes the previously set "right"
}

Upvotes: -2

Related Questions