javascriptで同じ処理をまとめる方法


javascriptで同じ処理をまとめるにはどのようにすればいいでしょうか。

[code]

    const but = document.getElementById("but");
    const trend = document.getElementById("trend");
    
    but.addEventListener("click", function () {
      if (trend.style.visibility == "visible") {
        // hiddenで非表示
        trend.style.visibility = "hidden";
      } else {
        // visibleで表示
        trend.style.visibility = "visible";
      }
    
    const but2 = document.getElementById("but2");
    const trend2 = document.getElementById("trend2");
    //初期表示は非表示
    trend2.style.visibility = "hidden";
    
    but2.addEventListener("click", function () {
      if (trend2.style.visibility == "visible") {
        // hiddenで非表示
        trend2.style.visibility = "hidden";
      } else {
        // visibleで表示
        trend2.style.visibility = "visible";
      }
    });
    
    const but3 = document.getElementById("but3");
    const trend3 = document.getElementById("trend3");
    //初期表示は非表示
    trend3.style.visibility = "hidden";
    
    but3.addEventListener("click", function () {
      if (trend3.style.visibility == "visible") {
        // hiddenで非表示
        trend3.style.visibility = "hidden";
      } else {
        // visibleで表示
        trend3.style.visibility = "visible";
      }
    });
    
[/code]



[code]

    document.getElementById('buttons').addEventListener('click', function (e) {
        if (e.target.dataset.trend == null) return;
        document.getElementById(e.target.dataset.trend).classList.toggle('hide');
    });
[/code]

[code]

    .hide {
        visibility: hidden;
    }
[/code]

[code]

    <div id="buttons">
      <button data-trend="trend1" type="button">trend1</button>
      <button data-trend="trend2" type="button">trend2</button>
      <button data-trend="trend3" type="button">trend3</button>
    </div>
    
    <div id="trend1">111</div>
    <div id="trend2" class="hide">222</div>
    <div id="trend3" class="hide">333</div>
[/code]

こんな感じでしょうか。

