Jump to content
Sign in to follow this  
seblondres

Removing margin when creating a new element

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

Share this post


Link to post
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

Share this post


Link to post
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);

Share this post


Link to post
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; }

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...