0

I have an HTML element that looks like this:

<p style=​"font:​12px verdana !important;​margin:20px !important;​">​…​</p>​

Now at some point I need to edit the margin attribute through Javascript. The code looks something like this:

document.getElementsByTagName('div')[3].getElementsByTagName('p')[0].style.margin='0'
document.getElementsByTagName('div')[3].getElementsByTagName('p')[0].style.marginLeft = '150px'

However, this isn't working. After I check the value of 'margin' and 'marginLeft' before and after the code, the values remain the same. If I use Google developer tools and manually change the Javascript then the issue is resolved. Can anyone tell me why the code above is not changing the value of the style? I also tried using setAttribute but that did not work either.

Art F
  • 3,992
  • 10
  • 49
  • 81

2 Answers2

0

You can try this with jquery:

$('selector').css('cssText','font:​12px verdana !important;​margin-left:150px !important;');

making of this way, it overrides your inline style, so be careful if you modify your style dinamically

Diego
  • 485
  • 3
  • 8
-1

You can use jquery for this its very easy:

$( ".selector" ).css( "background-color","#fff" );

OR you can access your element in this way

var elements = $( "body" ).find("div");
var p = elements[3].find("p");
$p[0].css("margin","0px");
$p[0].css("margin-left","150px");

if you don't want to use jQuery then you first check that you are accessing/selecting the right div and p tag you can alert the length of elements found and check is 3rd element have the one which you want to update?

saqibahmad
  • 962
  • 1
  • 9
  • 18