【JS / CSS】年度の絞り込みプルダウン

年ごとの絞り込みをするためのJSを作成しました。
ニュースなどに実装すると便利かと思います。

See the Pen Untitled by mtrad_ingu (@mtrad_ingu) on CodePen.

point1
selectタグの要素を作成する。
JSにidを書く。

[HTML]
<select id=”yearFilter”>
<option> value=”latest” selected>決算日を選択してください</option>
<option> value=”2025”>2025年</option>
<option> value=”2024”>2024年</option>
<option> value=”2023”>2023年</option>
</select>

[JS]
const select = document.getElementById(‘yearFilter’);

point2
2024年の表示にしたいものに data-year=”2024″ を追加する。
2023年、2022年なども同じようにする。
data-year=”2024″ を書いた要素のクラス名(year_block)をjsに書く。

[HTML]
<div class=”year_block” data-year=”2024″>

[JS]
const items = document.querySelectorAll(‘.year_block’);

point3
日付を書いた要素のクラス名(date)をjsに書く

[HTML]
<p class=”date”>2024年06月18日</p>

[JS]
const dateText = item.querySelector(‘.date’)?.textContent?.trim();

補足
初期に最新2年分表示されるようになっています。
下記の部分[now.getFullYear() – 2]→[now.getFullYear() – 1]とすると最新1年分になります。

oneYearAgo.setFullYear(now.getFullYear() – 2);
  • URLをコピーしました!
目次