Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading