-2

I am newer in javascript,so maybe my question will seem nail to some of you. I have this row it's create div element:

 <div id = "popUpWin" style = "width:' + width + 'px; height:' + height + 'px;"></div>;

My question is how to create this row dynamically using JavaScript?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • instead of asking SO for solutions for specific problems I would recommend studying the DOM API so you will have solutions for future problems too (teach a man to fish and all that): https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model – the8472 Jan 19 '15 at 15:21
  • possible duplicate of [Add elements to the DOM given plain text HTML using only pure JavaScript (no jQuery)](http://stackoverflow.com/questions/10309650/add-elements-to-the-dom-given-plain-text-html-using-only-pure-javascript-no-jqu) – Jonast92 Jan 19 '15 at 15:23

1 Answers1

1

There are at least a couple of ways to do this.

  1. Use document.createElement, which is one of the DOM API functions.

    // Create the element
    var d = document.createElement('div');
    
    // Set its ID
    d.id = "popUpWin";
    
    // Set the style properties on the element's `style` object
    d.style.width = width + "px";
    

    d.style.height = height + "px";

    ...and then presumably put it somewhere in the document using appendChild or insertBefore or similar on another element already in the document.

  2. Use insertAdjacentHTML on an existing element:

    theOtherElement.insertAdjacentHTML(
        'beforeend',
        '<div id = "popUpWin" style = "width:' + width + 'px; height:' + height + 'px;"></div>'
    );
    

    That example would add the div as a child right at the end of the existing element (without disturbing other elements already in it).

  3. Use innerHTML on an existing element, if you want to replace its content:

    theOtherElement.innerHTML =
        '<div id = "popUpWin" style = "width:' + width + 'px; height:' + height + 'px;"></div>';
    

    Note that that will remove any other elements inside theOtherElement and replace them with just that div.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875