Trick Shot
Trick Shot

Reputation: 29

How to select divs that has a specific HTML content that matches a value

I've created a calendar, and the days that are displayed are generated with a JavaScript loop:

for (let i = 1; i <= lastDay; i++) {
    if (
        i === new Date().getDate() &&
            date.getMonth() === new Date().getMonth()
    ) {
        days += `<div class="today">${i}</div>`;
    } else {
        days += `<div>${i}</div>`;
    }
}

It gives me this DOM result:

<div class="days">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  and so on...till 30 or 31, etc.
</div>

I'm bringing a repository data from my controller to this Twig template that returns some dates where sessions has been made.

So I would like to know how I would be able to read all these divs with JS that contains the day number, and mark only the ones that match the twig date (also date number so it matches), and so on the calendar, the user will be able to see every day case where he did a session.

I've thought of something like:

for (i = 0; i < $(".days div").length; i++) {
    if($( "div" ).html() == {{ session.dayNumber }}) {
        $("div").addClass("marked");
    }
}

But I can't seem to make it work well.


I succeeded to log all the days with:

const monElement = document.querySelector('.days');

for (let i = 0; i < monElement.children.length; i++) {
    console.log(monElement.children[i].textContent);
}

Upvotes: 0

Views: 105

Answers (1)

Mara Black
Mara Black

Reputation: 1751

I am not sure if this is what you wanted, but maybe you can use this as a start.

Since I don't know how you will store the days when the user visited the page, I used an array of 'days' and compare if the current day from loop is equal with the day from visited...

const visited = [2, 5, 8] // i am not sure how you will store the visited days..
const monElement = document.querySelector('.days')

for (let i = 0; i < monElement.children.length; i++) { // iterate through all elements
  let day = monElement.children[i].textContent;

  for (let v of visited) { // iterate through visited

    if (v == day) {
      monElement.children[i].innerHTML += ' - visited';
      monElement.children[i].classList.add("marked");
    }
  }

}
.days {
  width: 100px;
}

.marked {
  background-color: yellow;
}
<div class="days">
  <div> 1 </div>
  <div> 2 </div>
  <div> 3 </div>
  <div> 4 </div>
  <div> 5 </div>
  <div> 6 </div>
  <div> 7 </div>
  <div> 8 </div>
  <div> 9 </div>
  <div> 10 </div>
</div>

Upvotes: 1

Related Questions