Jump to content

Removing margin when creating a new element


seblondres

Recommended Posts

Hi guys,I've created this new element below. I managed to change the margin on the left, but I still cannot get rid off the top and bottom margin of the new element created, I've tried marginTop:0px but it doesn't work. Any suggestions?Thanks for your help.var p = document.getElementsByTagName("P").item(4);var newText = document.createTextNode("Print");var newElement = document.createElement('a'); newElement.setAttribute('href', 'http://www.google.fr'); newElement.setAttribute('style','margin-left:25px;'); newElement.appendChild(newText);p.parentNode.appendChild(newElement);

Link to comment
Share on other sites

You know, I've seen this "setAttribute" stuff a few times on this forum. I don't really trust it, personally. It works great in C# when you're working on a ASP.NET website, but in javascript, I think there are better ways. Try this instead:

newElement.href = "http://www.google.fr/";newElement.style.marginLeft = "25px";newElement.style.marginTop = "0px";newElement.style.backgroundColor = "#ff8c00";

Check out this reference for changing the styles throught the DOM:http://www.w3schools.com/htmldom/dom_obj_style.aspAnd this reference for changing properties of anchors:http://www.w3schools.com/htmldom/dom_obj_anchor.asp

Link to comment
Share on other sites

Ok, every style works except....the marginTop :/. I still have a space between the new element created and the paragraphe.Any other suggestions?var p = document.getElementsByTagName("P").item(4);var newText = document.createTextNode("Print");var newElement = document.createElement('a');newElement.href = "http://www.google.fr/";newElement.style.marginLeft = "25px";newElement.style.marginTop = "0px";newElement.style.backgroundColor = "#ff8c00"; newElement.appendChild(newText);p.parentNode.appendChild(newElement);

Link to comment
Share on other sites

I believe what you are seeing is the margin that is inherently part of the paragraph element (<p></p>). Try setting the CSS for the p to have zero margins. Or, follow the advice others have posted on this forum and set all the margins to 0 by default:

body { margin: 0; padding: 0; }

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...