jQuery document.createElement equivalent?

后端 未结 14 1735
暖寄归人
暖寄归人 2020-11-22 05:41

I\'m refactoring some old JavaScript code and there\'s a lot of DOM manipulation going on.

var d = document;
var odv = d.createElement(\"div\");
odv.style.di         


        
14条回答
  •  悲&欢浪女
    2020-11-22 06:03

    Not mentioned in previous answers, so I'm adding working example how to create element elements with latest jQuery, also with additional attributes like content, class, or onclick callback:

    const mountpoint = 'https://jsonplaceholder.typicode.com/users'
    
    const $button = $('button')
    const $tbody = $('tbody')
    
    const loadAndRender = () => {
      $.getJSON(mountpoint).then(data => {
    
        $.each(data, (index, { id, username, name, email }) => {
          let row = $('')
            .append($('', { text: id }))
            .append($('', {
              text: username,
              class: 'click-me',
              on: {
                click: _ => {
                  console.log(name)
                }
              }
            }))
            .append($('', { text: email }))
    
          $tbody.append(row)
        })
    
      })
    }
    
    $button.on('click', loadAndRender)
    .click-me {
      background-color: lightgrey
    }
    ID Username Email

提交回复
热议问题