0

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

1 Answer 1

1

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>

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

1 Comment

It worked but I have append part of the phrase the append the <br> then another part then the <br>

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.