javascriptcreateelementcreatetextnode

Adding inline tags within text node in javascript


Hi there this might be easy but I am new and just learning I need help with 2 problems.

First, when creating element using document.createElement() how to add class or id to that element?

---- found a solution for this problem of className = "" or id="" by adding a variable to differentiate the data originated from the array which I added and named id ----

Second, using createTextNode() to avoid using the innerHTML how to add the line breaker tag within?

Lets say I have an array of items = [{id: "item-1", name: "apple", price:1} , {id:"item-2" ,name : "mango", price:3}];

and I want to go through them with:

let data = document.getElementById("items-data"); 
items.forEach(item => {
                   let container = document.createElement("div"),  //here i want to add a defined id for further use
                       itemData = document.createTextNode(
                                  `item name : ${item.name} price: ${item.price}`); //here i want to add the br
    container.appendChild(itemData);
    container.id = item.id;
    data.appendChild(container);
};

Solution

  • Do you mean something like this:

    container.appendChild(document.createElement("br"));
    

    let base = document.querySelector(".base");
    
    let items = [{
      id: "item-1",
      name: "apple",
      price: 1
    }, {
      id: "item-2",
      name: "mango",
      price: 3
    }];
    
    items.forEach(item => {
      let container = document.createElement("div"), //here i want to add a defined id for further use
        itemData = document.createTextNode(
          `item name : ${item.name} price: ${item.price}`); //here i want to add the br
      container.appendChild(itemData);
      container.appendChild(document.createElement("br")); // <-- Add the line break to the node element
      container.id = item.id;
      base.appendChild(container);
    });
    <div class="base"></div>