1

I have this code:

function render(str)
{
    var main = document.createElement('div');
    with(main.style)
    {
          //style stuff here
    }

    main.appendChild(document.createTextNode(str));
    document.body.appendChild(main);

    setTimeout(function(){
        try{
            document.body.removeChild(main);
        }   catch(error){}
    },5000);
}

This render a message inside a div, an then hides after 5 secs.

How I can add a input text and image to this form? Since I'm not sure how I can do with pure JS.

1
  • Your code already shows how to do it, in the sense that adding an input is done the same way as adding a div (and you're already adding a div). Commented Mar 1, 2012 at 2:58

2 Answers 2

2

Something like this:

input

var input = document.createElement("input");
input.type = "text";
input.name = "person";

document.body.appendChild(input);

image img = document.createElement("img"); img.src = "logo.png";

document.body.appendChild(img);

See live example here:

I would suggest, however, learning and using something like jQuery - it's a great library that makes things like this a breeze.

See this SOq for a similar thing - creating input (type hidden in this case) element with jQuery and compare to plain JavaScript:

Sign up to request clarification or add additional context in comments.

7 Comments

I can do with jQuery, but pure JS is my next step :)
the code works, but i need to put inside the div created before, any ideas?
Sure - just append to main instead of document.body, here's an updated jsFiddle: jsfiddle.net/sM2Vd/2
That works like a charm. I appreciate your time, keep rockin'!
I would suggest you please remove your comments about jQuery. The OP is obviously a jQuery programmer, he's asking how to do it without jQuery since he's never programmed without jQuery.
|
0

Instead of using

with(main.style)
    {
          //style stuff here
    }

and doing several style manipulations,

write all the style assignments in one go

main.style.cssText='//css style string here

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.