Skip to content
Advertisement

Javascript : How can i add “×” in a button using javascript

I have a java script code that when i click submit button it will add list in my List items. but i want my list to have and “X” button or specifically “×” for deleting purpose. my code goes like this :

    const closeBtn = document.createElement('button');

    closeBtn.className = "closeBtn";

    closeBtn.type = "button";

    closeBtn.textContent = "×";

But instead of getting the X button i want, i get a button like this:

this

Advertisement

Answer

First use × and not $times;.

Second, use .innerHTML and not textContent.

const closeBtn = document.createElement('button');
closeBtn.className = "closeBtn";
closeBtn.type = "button";
closeBtn.innerHTML = "×" //String.fromCharCode("×");

document.querySelector('.content').append(closeBtn)
.closeBtn{
  font-size: 20px;
}
<div class="content"></div>

CSS Way:

You can find the Unicode for the character and use it with css. This is better as CSS is lighter compared to JS

.closeBtn{
  font-size: 20px;
}
.closeBtn::before {
  content: "2715";
}
<div class="content">
  <button class='closeBtn'></button>
</div>

Reference:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement