0

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

enter image description here

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);
4
  • DOM manipulation is the correct way. Have you done any research on how to create HTML elements in JavaScript? Commented Sep 21, 2020 at 14:56
  • but I couldn't get it done. How come? Could you show us what you've tried and what went wrong? Edit your question and add your JS. Commented Sep 21, 2020 at 14:59
  • Does this answer your question? info on javascript document.createElement() Commented Sep 21, 2020 at 15:00
  • NB: most of the time you don't need to call .setAttribute, you can do e.g. link2.href = .... Commented Sep 21, 2020 at 16:51

3 Answers 3

2

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}

P.S don't use setAttribute if you don't need to

Sign up to request clarification or add additional context in comments.

1 Comment

Great solution. I liked the level of sophistication. I will definitely bookmark it for future use.
0

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);

17 Comments

-1 you should use Element.textContent to add text content not innerHTML. You only use setAttribute for properties not defined by DOM and then only if you want the attribute to be parsed. id and src are already defined in the DOM there is no need to use setAttribute to change the values. Nor do you need to query for body it is a property of document eg document.body.appendChild
I would ask that you remove that -1: the set attribute is 100% correct if you are generating the elements in js... (he's not editing them via javascript, but creating them, so nothing has been defined). the query was to show how to append/grab things defined already. the above was just an example to the relevant code. although I agree with the textContent in general: innerHTML is useful to know about.
?? not editing them?? I do not see the distinction between creation and editing. DOM properties are always defined eg document.createElement('div').id === "" is true (same for img src) If they were not defined they would equal undefined document.createElement('div').randomProp === undefined is true. .100% not sure what that means. All things equal the simplest is always preferred document.body.appendChild(Object.assign(document.createElement('div'), {textContent: "hello world", id: "box"})));
const javascriptCREATEDELEMENT = document.createElement("div"); `````` console.log(javascriptCREATEDELEMENT.id) //undefined. ``````` javascriptCREATEDELEMENT.setAttribute("id", "test"); ```````` console.log(javascriptCREATEDELEMENT.id) //test. `````
You wrote "console.log(document.createElement("div").id) //undefined." what browser are you using. console.log(document.createElement("div").id === "");//true and console.log(document.createElement("div").id === undefined); // false. Set and Get attribute only for undefined properties that need parsing, or undefined properties you want to appear in the markup. And "...generally don't modify DOM elements with =" and by generally you mean.....?
|
-1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.