在页面加载后将类添加到元素的最后一个子元素

问题描述

我的代码:

  <script>

    fetch('http://127.0.0.1:8000/chatbot/fetch/')
      .then(response => response.json())
      .then(function (data) {
        console.log(data)

        if (data.choices !== '') {

          const htmlAnswer = data.answer.map(answer => {
            return `
              <button
                class="max-w-sm py-3 px-4 focus:outline-none text-blue-500 hover:bg-blue-100 text-center transition ease-in-out duration-300">
                ??‍? &nbsp; ${answer}
              </button>
            `
          }).join('')

          document.getElementById('server-message').innerHTML = `
            <div class="flex flex-col shadow rounded-lg my-3 max-w-sm border hover:border-indigo-300 hover:shadow-lg transition ease-in-out duration-300">
              <div class="mb-0 py-3 px-4 max-w-sm bg-gray-200 rounded-lg rounded-b-none select-none">
              ${data.question}
              </div>
              ${htmlAnswer}
            </div>
            `
          }
          document.addEventListener("DOMContentLoaded",function(){
          document.getElementById("server-message").lastElementChild.classList.add('rounded-b-lg');
          })

      })

  </script>

我想将类添加到父级的最后一个子级。我正在渲染JSON中的父元素和子元素。我该如何运作?

在将这些元素呈现到HTML之后,可能应该开始寻找子元素。我不知道该怎么做。

我在香草js中需要它。

解决方法

也许这会有所帮助。我检查了地图功能中的最后一项,并向其中添加了类

const answerLength = data.answer.length
  const htmlAnswer = data.answer.map((answer,index)=> {
// if this is the last element then add the class 
if(index+1 ==answerLength){

            return `
              <button
                class="max-w-sm py-3 px-4 focus:outline-none text-blue-500 hover:bg-blue-100 text-center transition ease-in-out duration-300 rounded-b-lg">
                ??‍? &nbsp; ${answer}
              </button>
            `
}
else{
            return `
              <button
                class="max-w-sm py-3 px-4 focus:outline-none text-blue-500 hover:bg-blue-100 text-center transition ease-in-out duration-300">
                ??‍? &nbsp; ${answer}
              </button>
            `
}
          }).join('')

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...