Search code examples
javascripthtmltags

I want a certain amount of code to be put in my HTML file with javascript on click of a button


Below given is the button, addItem is the function which will add the code

<button onclick="addItem()" class="list-group-item list-group-item-action py-2 ripple btn btn-primary">
          <i class="fas fa-chart-area fa-fw me-3"></i><span>➕  Add Product</span>
</button>

Below is the code i want to add:

<a href="#" class="list-group-item list-group-item-action flex-column align-items-start">
        <div class="d-flex w-100 justify-content-between">
          <h5 class="mb-1">Item 1</h5>
        </div>
        <p class="mb-1">Edible/Drinkable</small>`
</a><br>

Im trying to add the tag at a certain place in the html file onclick of a button


Solution

  • If you wish to add the provided HTML code when the button is clicked, you can change the addItem function to dynamically generate new HTML elements and append them to the desired position. Here's an example with JavaScript:

    <button onclick="addItem()" class="list-group-item list-group-item-action py-2 ripple btn btn-primary">
    <i class="fas fa-chart-area fa-fw me-3"></i><span>➕  Add Product</span>
    

    First step: create the new element

     var addItem = document.createElement('a');
     addItem.href = '#';
     addItem.className = 'list-group-item list-group-item-action flex-column align-items-start'
    

    Second step: create the innerHTML

    addItem.innerHTML = `
            <div class="d-flex w-100 justify-content-between">
             <h5 class="mb-1">Item 1</h5>
            </div>
            <p class="mb-1">Edible/Drinkable</p>
            `
    

    Locate the desired spot in the document and you may need to modify this selector. and append the item to the target location.