在指定的 DOM 元素中渲染给定的 DOM 树

这篇博客介绍了如何使用JavaScript创建和操作DOM元素。它详细阐述了一个名为`renderElement`的函数,该函数接受一个包含`type`和`props`的对象,用于创建文本或特定类型的元素,并能处理子元素和事件监听器。示例展示了如何创建一个带有点击事件的按钮元素。
摘要由CSDN通过智能技术生成
  • 将第一个参数分解为 typeprops。使用 type 确定给定元素是否为文本元素。
  • 根据元素的 type,使用 Document.createTextNode()Document.createElement() 创建 DOM 元素。
  • 根据需要,使用 Object.keys() 向 DOM 元素添加属性并设置事件监听器。
  • 使用递归渲染 props.children(如果有)。
  • 最后,使用 Node.appendChild() 将 DOM 元素附加到指定的容器中。
const renderElement = ({ type, props = {} }, container) => {
  const isTextElement = !type
  const element = isTextElement
    ? document.createTextNode('')
    : document.createElement(type)

  const isListener = p => p.startsWith('on')
  const isAttribute = p => !isListener(p) && p !== 'children'

  Object.keys(props).forEach(p => {
    if (isAttribute(p)) element[p] = props[p]
    if (!isTextElement && isListener(p))
      element.addEventListener(p.toLowerCase().slice(2), props[p])
  })

  if (!isTextElement && props.children && props.children.length)
    props.children.forEach(childElement =>
      renderElement(childElement, element)
    )

  container.appendChild(element)
}
const myElement = {
  type: 'button',
  props: {
    type: 'button',
    className: 'btn',
    onClick: () => alert('Clicked'),
    children: [{ props: { nodeValue: 'Click me' } }]
  }
}

renderElement(myElement, document.body)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值