user4609276
user4609276

Reputation:

Append text, when property value is equal to css class name

I'm trying to practice the state render view, where the state will determine where in the DOM an object is placed.

Basically, there are two HTML elements, both created in Javascript. Each will have classes .one and .two. There is also an array with two objects, with a slot property. The slot will determine which HTML element the names will be assigned to.

I tried looping through the state first, then nest a loop of the .name class. However when rendered, the first object is displayed first, when its slot is two; so ideally Tom appears in the second div.

I appreciate any input I could get. Thanks in advance!

Javascript

const body = document.querySelector('body');

const people = [
  {name: 'Tom', slot: 'two'},
  {name: 'Tim', slot: 'one'}
];

const createDiv = (arg) => {
  const div = document.createElement('div');

  div.classList.add('name', arg.slot);

  body.append(div);

  const namesClass = document.querySelectorAll('.name');

  people.forEach((ind)=>{
    namesClass.forEach((index)=>{
      if(index.classList.contains(ind.slot)){
        index.innerText = ind.name;
      };
    });
  });

  return div;
}

const render = () => {
  people.forEach(function(index){
    createDiv(index);
  });
}

render();

Upvotes: 1

Views: 462

Answers (1)

Alejandro De Cicco
Alejandro De Cicco

Reputation: 1236

Your if condition seems to be wrong. It could look like this:

if(index.classList.contains(ind.slot)){
  index.innerText = ind.name;
}

Now you have another problem: the divs are not created in order. First, you are creating the div for slot two, and then the div for slot one. The texts are inserted correctly, however the slots are in the wrong order. If you change people to look like this, it should work again:

const people = [
  {name: 'Tim', slot: 'one'},
  {name: 'Tom', slot: 'two'}
];

If you want the elements to be sorted automatically, you can change your people array to use numbers for the slots. That way, you can sort them:

var people = [
  {name: 'Tom', slot: 2},
  {name: 'Tim', slot: 1}
];

people.sort((personA, personB) => {
  return personA.slot - personB.slot
});

With those changes, your code should now work. Here's a working snippet:

const body = document.querySelector('body');

var people = [
  {name: 'Tom', slot: 2},
  {name: 'Tim', slot: 1}
];

people.sort((personA, personB) => {
  return personA.slot - personB.slot
});

const createDiv = (arg) => {
  const div = document.createElement('div');

  div.classList.add('name', arg.slot);

  body.append(div);

  const namesClass = document.querySelectorAll('.name');

  people.forEach((ind)=>{
    namesClass.forEach((index)=>{
      if(index.classList.contains(ind.slot)){
        index.innerText = ind.name;
      };
    });
  });

  return div;
}

const render = () => {
  people.forEach(function(index){
    createDiv(index);
  });
}

render();

Upvotes: 2

Related Questions