0

in function below i'm trying to add div block, but i can't set left position. alert function show message '600px'. on my screen this block has another position.

function show(){            
    if(document.getElementById('div1') == null){
        var div1 = document.createElement('div');
        div1.style.left = '600px';
        document.body.appendChild(div1);
        alert(div1.style.left);
    }
}

my first question here. so i don't know how to add code style

2
  • Use JQuery! It's your friend! Commented Jul 14, 2014 at 14:10
  • 2
    Don't use jQuery for trivial things, it is a massive library with abstractions that often get in the way of understanding what is going on. Commented Jul 14, 2014 at 14:11

3 Answers 3

2

You're not going to see anything visual on the page with your example for a couple reasons. First, your div does not contain anything, so it has no height or width. And second, you cannot position an element in the manner you are trying because it does not have display attribute absolute or relative. Try something like this:

function show(){

    if(document.getElementById('div1') == null){
      var div1 = document.createElement('div');
      div1.innerHTML = 'hi there';
      div1.style.left = '600px';
      div1.style.position = 'absolute';
      document.body.appendChild(div1);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

The left property only applies to elements which are positioned. For an element to be positioned, it must have a position property with a value other than static (which is the default).

Set it to relative, fixed or absolute as per your needs.

Comments

0

Your div will have 0 height/width as there is no child content. Use textContent or innerHTML to add content to the div.

Also, the left property will not apply unless you set the positioning to relative or absolute. This also goes for the other sides (right, top and bottom).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.