You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用唯一标识与getElementsByClassName实现点击生成带唯一类名的ul/li

实现点击按钮拆分文本并生成带有序类名的UL-LI结构

核心实现代码(main.js)

function show() {
  // 获取文本框内容
  const textContent = document.getElementById('myArea').value;
  // 按空格拆分单词,过滤空字符串(处理连续空格场景)
  const wordList = textContent.split(' ').filter(item => item.trim() !== '');

  // 移除之前生成的结果,避免重复创建
  document.querySelectorAll('[class^="word"]').forEach(el => el.remove());

  // 遍历单词生成对应结构
  wordList.forEach((word, idx) => {
    // 创建UL元素并设置类名
    const ul = document.createElement('ul');
    ul.className = `word${idx + 1}`;

    // 创建LI元素并填充单词
    const li = document.createElement('li');
    li.textContent = word;

    // 组装元素并添加到页面
    ul.appendChild(li);
    document.body.appendChild(ul);
  });
}

修正后的完整HTML代码

<!DOCTYPE html>
<head>
</head>
<body>
  <textarea id="myArea" class="rebaz" rows="4" cols="50">hello my name is rebaz</textarea>
  <button onclick="show();">Show content</button>
  
  <script src="./main.js" type="text/javascript"></script>
  <script src="cheack.js"></script>
</body>
</html>

实现说明

  1. 文本拆分处理:通过split(' ')拆分文本后,额外用filter过滤空字符串,避免连续空格导致生成空的列表项。
  2. 重复创建防护:每次点击按钮前,先移除页面上所有类名以word开头的UL元素,防止多次点击重复生成结构。
  3. 动态元素生成:遍历每个单词,依次创建UL和LI元素,给UL设置word1、word2...的类名,最后将组装好的元素添加到页面中。

运行后点击按钮,即可生成需求指定的DOM结构。

内容的提问来源于stack exchange,提问作者user23041361

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 05:17:27