最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Changing style of an element via vanilla Javascript - Stack Overflow

programmeradmin2浏览0评论
<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?

<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?

Share Improve this question edited Jan 18, 2017 at 23:42 Babak Naffas 12.6k3 gold badges35 silver badges51 bronze badges asked Nov 16, 2012 at 2:58 Ewr XcerqEwr Xcerq 1921 gold badge2 silver badges7 bronze badges 4
  • Any reason you're not doing this in your CSS? – Joseph Silber Commented Nov 16, 2012 at 2:59
  • 1 jQuery is JavaScript. Do you mean to ask how you can modify styles using stock JavaScript without any libraries? – Dai Commented Nov 16, 2012 at 3:00
  • 3 The fiddle you linked seems a little irrelevant. – Fabrício Matté Commented Nov 16, 2012 at 3:03
  • Thank you everyone anyway, I guess soon I'll bee a js expert :-D – Ewr Xcerq Commented Nov 16, 2012 at 3:07
Add a ment  | 

2 Answers 2

Reset to default 6
var elements = document.getElementsByTagName('a'),
    l = elements.length;

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

Here's the fiddle: http://jsfiddle/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/236pk/24

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"
}
发布评论

评论列表(0)

  1. 暂无评论