correct syntax for pure javascript

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.


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:

  • http://jsfiddle.net/sM2Vd/
  • 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:

  • Jquery - Create hidden form element on the fly

  • 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

    链接地址: http://www.djcxy.com/p/83498.html

    上一篇: 使用jQuery将数据形成数据库

    下一篇: 纯JavaScript的正确语法