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.

greenbandit
  • 2,267
  • 5
  • 30
  • 44
  • 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). – nnnnnn Mar 01 '12 at 02:58

2 Answers2

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:

Community
  • 1
  • 1
icyrock.com
  • 27,952
  • 4
  • 66
  • 85
  • I can do with jQuery, but pure JS is my next step :) – greenbandit Mar 01 '12 at 02:54
  • the code works, but i need to put inside the div created before, any ideas? – greenbandit Mar 01 '12 at 02:57
  • Sure - just append to `main` instead of `document.body`, here's an updated jsFiddle: http://jsfiddle.net/sM2Vd/2/ – icyrock.com Mar 01 '12 at 03:00
  • That works like a charm. I appreciate your time, keep rockin'! – greenbandit Mar 01 '12 at 03:05
  • 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. – slebetman Mar 01 '12 at 03:22
  • @slebetman Yes, but others who run into the same question I think will definitively benefit from knowing there is such a better alternative - removing the jQuery info would get rid of that benefit. – icyrock.com Mar 01 '12 at 03:27
  • In which case a single sentence would suffice. Everything else below that has no relevance to the question and should be edited out. – slebetman Mar 01 '12 at 04:06
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

kennebec
  • 102,654
  • 32
  • 106
  • 127