Create elements in javascript dynamically

前端 未结 2 759
轮回少年
轮回少年 2021-01-28 12:01

How can i create an element like this in javascript dynamically because i want to loop it while it is fetching content in the database.

相关标签:
2条回答
  • 2021-01-28 12:17

    With jQuery:

    For simplicity supouse only:

     <div class="card">
       <div class="card-image waves-effect waves-block waves-light">
        <img class="activator" src="images/office.jpg">
       </div>
       <p>other</p>
     </div>
    

    try

     $('<div>').class('card').append(
       $('<div>').class('card-image waves-effect').append(
         $('<img>').class('activator').src('images/office.jpg'),
         $('<p>').text(other)
       )
     );
    

    or with pure Javascript try:

    var div=document.createElement('div');
    div.className='card';
    var div2=document.createElement('div');
    div.appendChild(div2);
    etc...
    
    0 讨论(0)
  • 2021-01-28 12:22

    I have successfully converted the html elements to jquery thanks to @Emilio

    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
     <script>
         $(document).ready(function () {
    
            var card = $('<div>', { class: 'row' }).append($('<div>', { class: 'col s4' }).append($('<div>', { class: 'card' }).append(
           $('<div>', { class: 'card-image waves-effect waves-block waves-light' }).append(
             $('<img>', { class: 'activator', src: 'img/products/Xiaomi-Mi-4.jpg'})
           ), $('<div>', { class: 'card-content' }).append(
                 $('<span>', { class: 'card-title activator grey-text text-darken-4', text: 'Card Title' }).append($('<i>', { class: 'material-icons right' }).text('more_vert'))
                 , $('<p>').append($('<a>', { href: '#' }).text('This is Link'))
           ), $('<div>', { class: 'card-reveal' }).append($('<span>', { class: 'card-title activator grey-text text-darken-4', text: 'Card Title' }).append($('<i>', { class: 'material-icons right' }).text('close')), $('<p>').text('Here is some more information about this product that is only revealed once clicked on.'))
    
         )))
    
            $(document.body).append(card);
         });
    </script>
    
    0 讨论(0)
提交回复
热议问题