简体   繁体   中英

How can I create HTML tags using Javascript?

I have this code that I want to create using JavaScript since I will be using it in more than one file. I thought about using:after with CSS but it didn't work. Then I thought about using the DOM manipulation to create the HTML tags but I couldn't get it done.

can anyone help me?

The image below illustrate what I am trying to accomplish

  1. the main div tag
  2. the div tag inside main div tag
  3. the div tags I want to create using JavaScript

在此处输入图像描述

Thanks in advance,

Thanks everybody for the help. Here is what I got from your response

//CREATE MENU DIVs

    const mainbody = document.querySelector('body') //or target div

    const divbtn = document.createElement('div');
    divbtn.setAttribute('id','btn');

    const img = document.createElement('img');
    img.setAttribute('src', 'https://thiagoprado.com/demo/learning/overlay-menu.png');
    img.setAttribute('id','menu');
    img.style.display = "block";

    const img2 = document.createElement('img');
    img2.setAttribute('src', 'https://thiagoprado.com/demo/learning/close-menu.png');
    img2.setAttribute('id','x');
    img2.style.display = "none";

    divbtn.appendChild(img);
    divbtn.appendChild(img2);
    //canvasDIV.appendChild(div);
    document.getElementById("c2canvasdiv").appendChild(divbtn);


    // second main DIV

    const divbox = document.createElement('div');
    divbox.setAttribute('id','box');

    const divItems = document.createElement('div');
    divItems.setAttribute('id','items');

    const divItem = document.createElement('div');
    divItem.setAttribute('class','item');

    const divItem2 = document.createElement('div');
    divItem2.setAttribute('class','item');
    //divItem2.setAttribute('id','item2');

    const link1 = document.createElement('a');
    link1.setAttribute('href','https://thiagoprado.com/demo/learning/');

    const img3 = document.createElement('img');
    img3.setAttribute('src', 'https://thiagoprado.com/demo/learning/home-60x60.png');


    const link2 = document.createElement('a');
    link2.setAttribute('href','#');

    const img4 = document.createElement('img');
    img4.setAttribute('src', 'https://thiagoprado.com/demo/learning/logo-60x60.png');

    divbox.appendChild(divItems);
    divItems.appendChild(divItem);
    divItem.appendChild(link1);
    link1.appendChild(img3);

    divItems.appendChild(divItem2);
    divItem2.appendChild(link2);
    link2.appendChild(img4);        

    document.getElementById("c2canvasdiv").appendChild(divbox);

Dynamic HTML

DOM manipulation via javascript is the quickest way to generate dynamic content, however it can be exceedingly verbose and thus hard to read, maintain, and keep free of bugs.

When you write code you should always be thinking about keeping the code D.R.Y.

Your code example has 42 lines, 12 temp variables. Looking at it in a glance it gives no clue to the structure you are creating. And what if there is a design changes, that's a lot of work if you come back in a month and make changes.

  • Use functions to do repetitive tasks
  • Think about how you can structure you data so its easy to extract information from it.
  • Avoid bad coding habits.

Example

Using DRY principles

  • Creating 3 functions for common tasks create, append and query,
  • Storing the url base in a variable (avoiding chance of typo when entering long strings)
  • Structuring the code such that it reflect what it is creating

The result is more code of better quality in less time.

The following does exactly the same as you code example.

const url = "https://thiagoprado.com/demo/learning/";
const element = (tag, props = {}) => Object.assign(document.createElement(tag), props);
const append = (par, ...sibs) => sibs.reduce((p, sib) => (p.appendChild(sib), p), par);
const queryEl = (qStr, el = document) => el.querySelector(qStr);

append(queryEl("#c2canvasdiv"),
  append(element("div", {id: "btn"}),
    element("img", {id: "menuEl", src: url + "overlay-menu.png", className: "block"}),
    element("img", {id: "closeEl", src: url + "close-menu.png", className: "hide"}),
  ),
  append(element("div", {id: "box"}),
    append(element("div", {id: "items"}),
      append(element("div", {className: "item"}),
        append(element("a", {href: url}), element("img", {src: url + "home-60x60.png"}))
      )
    ),
    append(element("div", {className: "item"}),
      append(element("a", {href: "#"}), element("img", {src: url + "logo-60x60.png"}))
    )
  )
);

Oh and CSS rules as in-lining styles are a very bad habit

.hide {display: none}
.block {display: block}

PS don't use setAttribute if you don't need to

here is the javascript you are looking for. a small example of creating elements via js. by reading this. you should be able to accomplish what you want.

const root = document.querySelector('body') //or target div
const div = document.createElement('div');
div.innerHTML = "text for div";
const img = document.createElement('img');
img.setAttribute('src', 'urlString');
div.setAttribute('id','box');

div.appendChild(img);
root.appendChild(div);

Use document.createElement, assign with innerHTML and ID and finally append node to parent element.

https://www.w3schools.com/JSREF/met_document_createelement.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM