javascriptcssbootstrap-icons

How to change bootstrap icon's attributes using javascript


I need -

  1. To create a bootstrap icon (heart) when DOM content is loaded
  2. When the icon is clicked, the heart icon fills with red (Here I use heart-fill icon)
  3. Both of the icons to be larger than the original

document.addEventListener('DOMContentLoaded', function () {
      var heart = document.createElement('i')
      heart.className = 'bi bi-heart'
      document.querySelector('#posts').append(heart)
      heart.onclick = function () {
        this.className = 'bi bi-heart-fill'
        this.setAttribute('fill', 'red')
      }
    } )
<head><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css"></head>
<body><div id="posts"></div></body>

When I click the heart, it fills with black, not red. I also do not know how to make it larger by increasing the value of width and height. I saw other questions related to this, but none of them solve my problem.


Solution

  • First off, since you used bootstrap icons and they are just working with the CSS content property, you do not have access to the fill property within them so it won't work as expected, alternatively, you should work with color and font-size property to achieve what you looking for.

    In order to use it within javascript, You need to use style property and then access their attributes (like color and fontSize) within it. With the same solution, you can change the size of them with the font-size property.

    Here is the final product of the above approaches:

    document.addEventListener('DOMContentLoaded', function() {
      var heart = document.createElement('i')
      heart.className = 'bi bi-heart'
      document.querySelector('#posts').append(heart)
      heart.onclick = function() {
        this.className = 'bi bi-heart-fill'
        this.style.color = 'red'
        this.style.fontSize = '24px'
      }
    })
    <head>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
    </head>
    
    <body>
      <div id="posts"></div>
    </body>