admin管理员组

文章数量:1296258

I've been trying to use pure JavaScript (no jQuery) to recreate HTML content within the container. But, nothing shows up on the webpage when I run. I did a lot of research online, but still no luck. Could anyone help me to take a look?

p.s. Sorry about my code is long and messy. If you could help me point out which part of function or format I did wrong and tell me the correct way that would be great! Thank you!

Here is the original code I am trying to duplicate:

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <h3>Nothing clicked yet!</h3>
      <button type="button" class="btn btn-default btn-lg">Star</button>
      <hr>
      <div>
        <div class="btn-group">
          <button type="button" class="btn btn-default">1</button>
          <button type="button" class="btn btn-default">2</button>
          <button type="button" class="btn btn-default">3</button>
          <button type="button" class="btn btn-default">4</button>
        </div>
        <div class="btn-group">
          <button type="button" class="btn btn-default">5</button>
          <button type="button" class="btn btn-default">6</button>
          <button type="button" class="btn btn-default">7</button>
        </div>
        <div class="btn-group">
          <button type="button" class="btn btn-default">8</button>
        </div>
      </div>
      <hr>
      <div>
        <div class="btn-group btn-group-lg">
          <button type="button" class="btn btn-default">Left</button>
          <button type="button" class="btn btn-default">Middle</button>
          <button type="button" class="btn btn-default">Right</button>
        </div>
      </div>
    </div>
  </div>
</div>

Here is what I have so far:

function myFunction() {
  var makeDiv = document.createElement('DIV');
  var makeHead = document.createElement('H3');
  var makeBTN = document.createElement('BUTTON');

  var swapH3 = function swap() {
      //locate button textNode then use it to replace the text inside of h3;
  };

  var rowDiv = document.getElementById("container").appendChild("makeDiv");
  rowDiv.className = "row";
  rowDiv.id = "row";

  var colDiv = document.getElementById('row').appendChild('makeDiv');
  colDiv.className = "col-md-12";
  colDiv.id = "col";

  var head = document.getElementById('col').appendChild('makeHead');
  head.id = "head";
  head.createTextNode('Nothing clicked Yet!');

  var btn0 = document.getElementById('col').appendChild('makeBTN');
  btn0.id = "btn0";
  btn0.className = "btn btn-default btn-lg on";
  btn0.createTextNode = ('star');
  btn0.type = "button";
  btn0.onclick = swapH3;

  document.getElementById('col').appendChild(document.createElement(HR));

  var btng1 = document.getElementById('col').appendChild('makeDIV');
  btng1.id = 'btng1';

  document.getElementById('col').appendChild(document.createElement(HR));

  var btng2 = document.getElementById('col').appendChild('makeDIV');
  btng2.id = 'btng2';

  var btngA = document.getElementById('btng1').appendChild('makeDIV');
  btngA.id = 'btngA';
  btngA.className = 'btn-group';

  var btngB = document.getElementById('btng1').appendChild('makeDIV');
  btngB.id = 'btngB';
  btngB.className = 'btn-group';

  var btngC = document.getElementById('btng1').appendChild('makeDIV');
  btngC.id = 'btngC';
  btngC.className = 'btn-group';

  var btngD = document.getElementById('btng2').appendChild('makeDIV');
  btngD.id = 'btngD';
  btngD.className = 'btn-group btn-group-lg';

  var btn1 = document.getElementById('btngA').appendChild('makeBTN');
  btn1.className = 'btn btn-default';
  btn1.type = 'button';
  btn1.createTextNode = ('1');
  btn1.onclick = swapH3;

  var btn2 = document.getElementById('btngA').appendChild('makeBTN');
  btn2.className = 'btn btn-default';
  btn2.type = 'button';
  btn2.createTextNode = ('2');
  btn2.onclick = swapH3;

  var btn3 = document.getElementById('btngA').appendChild('makeBTN');
  btn3.className = 'btn btn-default';
  btn3.type = 'button';
  btn3.createTextNode = ('3');
  btn3.onclick = swapH3;

  var btn4 = document.getElementById('btngA').appendChild('makeBTN');
  btn4.className = 'btn btn-default';
  btn4.type = 'button';
  btn4.createTextNode = ('4');
  btn4.onclick = swapH3;

  var btn5 = document.getElementById('btngB').appendChild('makeBTN');
  btn5.className = 'btn btn-default';
  btn5.type = 'button';
  btn5.createTextNode = ('5');
  btn5.onclick = swapH3;

  var btn6 = document.getElementById('btngB').appendChild('makeBTN');
  btn6.className = 'btn btn-default';
  btn6.type = 'button';
  btn6.createTextNode = ('6');
  btn6.onclick = swapH3;

  var btn7 = document.getElementById('btngB').appendChild('makeBTN');
  btn7.className = 'btn btn-default';
  btn7.type = 'button';
  btn7.createTextNode = ('7');
  btn7.onclick = swapH3;

  var btn8 = document.getElementById('btngC').appendChild('makeBTN');
  btn8.className = 'btn btn-default';
  btn8.type = 'button';
  btn8.createTextNode = ('8');
  btn8.onclick = swapH3;

  var btnLeft = document.getElementById('btngD').appendChild('makeBTN');
  btnLeft.className = 'btn btn-default';
  btnLeft.type = 'button';
  btnLeft.createTextNode = ('Left');
  btnLeft.onclick = swapH3;

  var btnMiddle = document.getElementById('btngD').appendChild('makeBTN');
  btnMiddle.className = 'btn btn-default';
  btnMiddle.type = 'button';
  btnMiddle.createTextNode = ('Middle');
  btnMiddle.onclick = swapH3;

  var btnRight = document.getElementById('btngD').appendChild('makeBTN');
  btnRight.className = 'btn btn-default';
  btnRight.type = 'button';
  btnRight.createTextNode = ('Right');
  btnRight.onclick = swapH3;
}
<link href=".3.6/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container" id="container">
</div>

I've been trying to use pure JavaScript (no jQuery) to recreate HTML content within the container. But, nothing shows up on the webpage when I run. I did a lot of research online, but still no luck. Could anyone help me to take a look?

p.s. Sorry about my code is long and messy. If you could help me point out which part of function or format I did wrong and tell me the correct way that would be great! Thank you!

Here is the original code I am trying to duplicate:

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <h3>Nothing clicked yet!</h3>
      <button type="button" class="btn btn-default btn-lg">Star</button>
      <hr>
      <div>
        <div class="btn-group">
          <button type="button" class="btn btn-default">1</button>
          <button type="button" class="btn btn-default">2</button>
          <button type="button" class="btn btn-default">3</button>
          <button type="button" class="btn btn-default">4</button>
        </div>
        <div class="btn-group">
          <button type="button" class="btn btn-default">5</button>
          <button type="button" class="btn btn-default">6</button>
          <button type="button" class="btn btn-default">7</button>
        </div>
        <div class="btn-group">
          <button type="button" class="btn btn-default">8</button>
        </div>
      </div>
      <hr>
      <div>
        <div class="btn-group btn-group-lg">
          <button type="button" class="btn btn-default">Left</button>
          <button type="button" class="btn btn-default">Middle</button>
          <button type="button" class="btn btn-default">Right</button>
        </div>
      </div>
    </div>
  </div>
</div>

Here is what I have so far:

function myFunction() {
  var makeDiv = document.createElement('DIV');
  var makeHead = document.createElement('H3');
  var makeBTN = document.createElement('BUTTON');

  var swapH3 = function swap() {
      //locate button textNode then use it to replace the text inside of h3;
  };

  var rowDiv = document.getElementById("container").appendChild("makeDiv");
  rowDiv.className = "row";
  rowDiv.id = "row";

  var colDiv = document.getElementById('row').appendChild('makeDiv');
  colDiv.className = "col-md-12";
  colDiv.id = "col";

  var head = document.getElementById('col').appendChild('makeHead');
  head.id = "head";
  head.createTextNode('Nothing clicked Yet!');

  var btn0 = document.getElementById('col').appendChild('makeBTN');
  btn0.id = "btn0";
  btn0.className = "btn btn-default btn-lg on";
  btn0.createTextNode = ('star');
  btn0.type = "button";
  btn0.onclick = swapH3;

  document.getElementById('col').appendChild(document.createElement(HR));

  var btng1 = document.getElementById('col').appendChild('makeDIV');
  btng1.id = 'btng1';

  document.getElementById('col').appendChild(document.createElement(HR));

  var btng2 = document.getElementById('col').appendChild('makeDIV');
  btng2.id = 'btng2';

  var btngA = document.getElementById('btng1').appendChild('makeDIV');
  btngA.id = 'btngA';
  btngA.className = 'btn-group';

  var btngB = document.getElementById('btng1').appendChild('makeDIV');
  btngB.id = 'btngB';
  btngB.className = 'btn-group';

  var btngC = document.getElementById('btng1').appendChild('makeDIV');
  btngC.id = 'btngC';
  btngC.className = 'btn-group';

  var btngD = document.getElementById('btng2').appendChild('makeDIV');
  btngD.id = 'btngD';
  btngD.className = 'btn-group btn-group-lg';

  var btn1 = document.getElementById('btngA').appendChild('makeBTN');
  btn1.className = 'btn btn-default';
  btn1.type = 'button';
  btn1.createTextNode = ('1');
  btn1.onclick = swapH3;

  var btn2 = document.getElementById('btngA').appendChild('makeBTN');
  btn2.className = 'btn btn-default';
  btn2.type = 'button';
  btn2.createTextNode = ('2');
  btn2.onclick = swapH3;

  var btn3 = document.getElementById('btngA').appendChild('makeBTN');
  btn3.className = 'btn btn-default';
  btn3.type = 'button';
  btn3.createTextNode = ('3');
  btn3.onclick = swapH3;

  var btn4 = document.getElementById('btngA').appendChild('makeBTN');
  btn4.className = 'btn btn-default';
  btn4.type = 'button';
  btn4.createTextNode = ('4');
  btn4.onclick = swapH3;

  var btn5 = document.getElementById('btngB').appendChild('makeBTN');
  btn5.className = 'btn btn-default';
  btn5.type = 'button';
  btn5.createTextNode = ('5');
  btn5.onclick = swapH3;

  var btn6 = document.getElementById('btngB').appendChild('makeBTN');
  btn6.className = 'btn btn-default';
  btn6.type = 'button';
  btn6.createTextNode = ('6');
  btn6.onclick = swapH3;

  var btn7 = document.getElementById('btngB').appendChild('makeBTN');
  btn7.className = 'btn btn-default';
  btn7.type = 'button';
  btn7.createTextNode = ('7');
  btn7.onclick = swapH3;

  var btn8 = document.getElementById('btngC').appendChild('makeBTN');
  btn8.className = 'btn btn-default';
  btn8.type = 'button';
  btn8.createTextNode = ('8');
  btn8.onclick = swapH3;

  var btnLeft = document.getElementById('btngD').appendChild('makeBTN');
  btnLeft.className = 'btn btn-default';
  btnLeft.type = 'button';
  btnLeft.createTextNode = ('Left');
  btnLeft.onclick = swapH3;

  var btnMiddle = document.getElementById('btngD').appendChild('makeBTN');
  btnMiddle.className = 'btn btn-default';
  btnMiddle.type = 'button';
  btnMiddle.createTextNode = ('Middle');
  btnMiddle.onclick = swapH3;

  var btnRight = document.getElementById('btngD').appendChild('makeBTN');
  btnRight.className = 'btn btn-default';
  btnRight.type = 'button';
  btnRight.createTextNode = ('Right');
  btnRight.onclick = swapH3;
}
<link href="https://maxcdn.bootstrapcdn./bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container" id="container">
</div>
Share Improve this question edited Jul 22, 2016 at 14:24 Makyen 33.4k12 gold badges92 silver badges125 bronze badges asked Jul 21, 2016 at 23:59 wen zhangwen zhang 1151 gold badge2 silver badges6 bronze badges 9
  • And where are you calling myFunction – Hackerman Commented Jul 22, 2016 at 0:04
  • 1 It's hard to assist because it's difficult to tell what your intent is - for what purpose would you want to re-create each HTML element? innerHTML will allow you to get/set the contents of an HTML element, so why would you want to do this? developer.mozilla/en-US/docs/Web/API/Element/innerHTML – Toby Commented Jul 22, 2016 at 0:07
  • What error message are you getting? Also not sure that var rowDiv = document.getElementById("container").appendChild("makeDiv"); is valid, shouldn't it be var rowDiv = document.getElementById("container").appendChild(makeDiv);? – Nicholas Hirras Commented Jul 22, 2016 at 0:07
  • It is a challenge that I am working on, the challenge require me to just use JavaScript and DOM to recreate HTML content. – wen zhang Commented Jul 22, 2016 at 0:33
  • Your JavaScript is adding attributes to the HTML which are not contained in the HTML you have given as what you desire. What is it that you actually desire to have created (i.e. do you want the HTML with or without these extra attributes)? – Makyen Commented Jul 22, 2016 at 2:07
 |  Show 4 more ments

3 Answers 3

Reset to default 7

Using JavaScript to create HTML:

Creating HTML elements:
Each HTML element must first be specifically created.

There are a variety of ways to do this. The most monly used are:

  • Use document.createElement() to create the element.
    var myDiv = document.createElement("div");
    myDiv will be a reference to the element you just created. The element will not yet be part of the DOM. If you want it to be displayed, you will need to add it to the DOM.
  • Assign an HTML string to the innerHTML property of another element.
    containingElement.innerHTML = "<div id="divA"><div id="divB">Some Text"</div></div>";
    There are a variety of potential issues with directly adding HTML text to the DOM. In particular, there are security issues if any part of the HTML text you are adding is not derived from strings hard coded in your program.
    Depending on what you are assigning, there can be performance issues with repeatedly changing large parts of the DOM by assigning to innerHTML.
  • Assign text to the textContent property of another element. This will remove any other children and create a single text node as the only child for the element.
    elementToHaveText.textContent = "The text I want in this element."
  • Use cloneNode() to create a copy of a node, or a node and all its children.
    var theCopy = nodeToCopy.cloneNode() //thecopy will be a copy of nodeToCopy.
    var theCopy = nodeToCopy.cloneNode(true) //Create a copy of nodeToCopy and all children.
  • Use insertAdjacentHTML() to create elements and insert them into the DOM using HTML text at the same time. This method provides more control over inserting the elements generated from HTML text. In many/some cases it will be faster than other types of node generation and insertion. The HTML is inserted in relation to a reference element. You can insert the HTML, before, as children (either at the beginning or end), or after the reference element.
    refEl.insertAdjacentHTML('afterend',"<div id="A"><div id="B">Some Text"</div></div>"); This method has the same security concerns and assigning to innerHTML regarding direct conversion HTML text that is not hard coded in your program.

There are additional ways to create HTML elements. You will want to look at the documentation for documents, nodes and elements.

Adding elements to the DOM:
In order for an HTML element to be visible it must be added to the DOM. There are multiple ways to add an element to the DOM. The most monly used are:

  • Use a methodology that both creates the nodes and inserts them into the DOM at the same time. You can do so with:
    • Assign an HTML string to the innerHTML property of another element.
    • Use insertAdjacentHTML() to create and insert elements into the DOM using HTML text.
  • Use appendChild() to add a child to the end of an element's list of children.
    element.appendChild(aChild);
  • Use insertBefore() to add a child to a parent prior to another child of that parent.
    parentNode.insertBefore(aChild, referenceChild);
  • Use replaceChild() to replace a child of a parent node.
    parentNode.replaceChild(aChild, oldChild);

As with creating elements, there are additional ways to add elements to the DOM. You will want to look at the documentation for documents, nodes and elements.

You can not use the same element in the DOM multiple times. If you try to do so, the element which you are trying to add in a second place will be moved from its current place in the DOM to the place where you are inserting it. This is the normal way to move an element rather than explicitly removing it and then re-adding it in another location.

If you want to add elements which have children, you either have to create them all at one time using one of the methodologies that creates and inserts HTML text, or you need to have references to the nodes you create in order to use them when adding children later. It is significantly more efficient to have a variable which is a reference to the parent node you have created rather than having to search the DOM for that node in order to add children.

Regarding your code:

  • You are passing a string to appendChild() when you should be passing an element.
  • You are using document.getElementById() to try to get references to elements which you have just created.
    • None of your elements have IDs in the HTML. You appear to be adding IDs just so you can use document.getElementById() to find the elements you created.
    • If you need a reference to an element you created, you should be keeping the reference you get from creating the element. It is bad practice to perform a bunch of extra processing (searching for an element) which is pletely unneeded.
    • You should never need to perform a call to document.getElementById() to get a reference to an element that you have created in the same function in which you need the reference.
  • You are using createTextNode().
    • This is a method of document, not element.
    • For your use, setting the only child node to be a single text child node, it is more efficient to just assign to Element.textContent.
  • You have created the variables makeDiv, makeHead, and makeBTN which you appear to be trying to use multiple times as a different element each time you are referring to the variable. It does not work the way you have coded it. As written, there is only one element of each type created. You can not use the same element in multiple locations in the DOM.
    • Each element must be specifically created. While there are other ways to create separate elements (e.g. cloneNode()), the most mon is document.createElement().
  • You have written way too much linear code. Your elements are very similar. You should code this such that creating them is modular.

From your question, it is unclear to me if you are attempting to create the entirety of the HTML code you have provided, or if you are trying to create everything from the <div> with class="row" and add it to the DOM within a <div> with class="container". I have assumed that you are attempting to create the entirety of the HTML.

I have also assumed that you want the HTML you have listed in the question without the additional attributes which are in your JavaScript.

Here is some code that creates the HTML you are looking for:

function createDesiredHtmlElements() {
    function createDiv(theClass) {
        var div = document.createElement("div");
        if(typeof theClass === "string") {
            div.className = theClass;
        }
        return div;
    }
    function createButton(text,theClass,type) {
        var button = document.createElement("button");
        type = (typeof type === "undefined") ? "button" : type;
        theClass = (typeof theClass === "undefined") ? "btn btn-default" : theClass;
        button.setAttribute("type",type);
        button.className = theClass;
        button.textContent = text;
        return button;
    }
    function createButtonGroupDiv(buttonsText,divClass) {
        buttonsText = (typeof buttonsText === "string") ? [buttonsText] : buttonsText;
        divClass = (typeof divClass === "undefined") ? "btn-group" : divClass;
        var div = createDiv(divClass);
        if(Array.isArray(buttonsText)) {
            buttonsText.forEach(function(buttonText) {
                div.appendChild(createButton(buttonText));
            });
        }
        return div;
    }
    //Actually create the HTML:
    var mainDiv = createDiv("container");
    var rowDiv = mainDiv.appendChild(createDiv("row"));
    var colDiv = rowDiv.appendChild(createDiv("col-md-12"));
    colDiv.appendChild(document.createElement("h3")).textContent = "Nothing clicked yet!";
    colDiv.appendChild(createButton("Star","btn btn-default btn-lg"));
    colDiv.appendChild(document.createElement("hr"));
    var midDiv = colDiv.appendChild(createDiv());
    midDiv.appendChild(createButtonGroupDiv(["1","2","3","4"]));
    midDiv.appendChild(createButtonGroupDiv(["5","6","7"]));
    midDiv.appendChild(createButtonGroupDiv("8"));
    colDiv.appendChild(document.createElement("hr"));
    var midDiv2 = colDiv.appendChild(createDiv());
    midDiv2.appendChild(createButtonGroupDiv(["Left","Middle","Right"]
                                             ,"btn-group btn-group-lg"));
    return mainDiv;
}

If you then do the following:

var theDiv = createDesiredHtmlElements();
console.log(theDiv.outerHTML);

You will see the HTML:

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <h3>Nothing clicked yet!</h3>
      <button class="btn btn-default btn-lg" type="button">Star</button>
      <hr>
      <div>
        <div class="btn-group">
          <button class="btn btn-default" type="button">1</button>
          <button class="btn btn-default" type="button">2</button>
          <button class="btn btn-default" type="button">3</button>
          <button class="btn btn-default" type="button">4</button>
        </div>
        <div class="btn-group">
          <button class="btn btn-default" type="button">5</button>
          <button class="btn btn-default" type="button">6</button>
          <button class="btn btn-default" type="button">7</button>
        </div>
        <div class="btn-group">
          <button class="btn btn-default" type="button">8</button>
        </div>
      </div>
      <hr>
      <div>
        <div class="btn-group btn-group-lg">
          <button class="btn btn-default" type="button">Left</button>
          <button class="btn btn-default" type="button">Middle</button>
          <button class="btn btn-default" type="button">Right</button>
        </div>
      </div>
    </div>
  </div>
</div>

Note that the code above does not actually put the created HTML into the DOM. You have not specified what you want done with the HTML once it is created.

There are many great template system out there. Personally, I like handlebarsjs, though I am sure others have excellent favorites as well. You should check them out.

That aside, I find that it is sometimes easier to just build the html as text and use it rather than build the individual DOM nodes.

var html = [];
html.push("<div class=\"row\">");
  html.push("<div class=\"col-xs-6\">A</div>");
  html.push("<div class=\"col-xs-6\">B</div>");
html.push("</div>");

document.getElementById("container").innerHTML = html.join("");
.col-xs-6 {
  min-height: 3em !important;
  border: solid 1px;
  background-color: aliceblue;
}
<link href="https://maxcdn.bootstrapcdn./bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<div id="container" class="container"></div>

<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn./bootstrap/3.3.6/js/bootstrap.min.js">></script>

You have to call document.createElement every time want to append an element. Also, you are not supposed to pass a string to appendChild. You are supposed to pass in what document.createElement returns. Also, createTextNode is a function of document, and it returns a text node that you have to append to the element yourself. Your code should look something like:

  var rowDiv = document.createElement("DIV");
  document.getElementById("container").appendChild(rowDiv);
  rowDiv.className = "row";
  rowDiv.id = "row";

  var colDiv = document.createElement("DIV");
  document.getElementById("row").appendChild(colDiv);
  colDiv.className = "col-md-12";
  colDiv.id = "col";

  var head = document.createElement("H3");
  document.getElementById("col").appendChild(head);
  head.id = "head";
  head.appendChild(document.createTextNode('Nothing clicked Yet!'));

本文标签: How do I use just JavaScript to create HTML codeStack Overflow