Creating a Button with Icon and Text in TypeScript: A step-by-step guide

I attempted to create a button with both text and an icon. Initially, I tried doing it in HTML.

    <button>
      <img src="img/favicon.png" alt="Image" width="30px" height="30px" >
      Button Text
    </button>

Next, I attempted to achieve the same using TypeScript.

    const btn = document.createElement("button");
    const img=document.createElement("img");
    img.src=`img/${favicon.png}`;
    btn.appendChild(img);
    btn.textContent=label;

However, after adding the label, the icon disappeared.

My current solution involves:

    const btn = document.createElement("button");
    const img=document.createElement("img");
    img.src=`img/${favicon.png}`;
    btn.appendChild(img);
    const span=document.createElement("span");
    btn.appendChild(span)
    span.textContent=label

...

Unfortunately, this solution has resulted in other issues. Is there anyone who knows of a better alternative? I prefer not to rely on external libraries like awesome icons.

Answer №1

The original JavaScript solution presented here is flawed because using textContent will erase any existing content within the button element. For more information, refer to https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent

To achieve a similar result in JavaScript as shown with HTML, one can utilize the Text object instead. Check out https://developer.mozilla.org/en-US/docs/Web/API/Text for details.

Test it out on Repl:

Snippet of code:

    const btn = document.createElement("button");
    const img = document.createElement("img");
    const text = new Text(" Button text");
    img.src = `img/favicon.png`;
    img.alt = "Icon";
    img.width = "10";
    img.height = "10";
    btn.appendChild(img);
    btn.appendChild(text);
    document.body.appendChild(btn);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The typography text exceeds the boundaries of the Material-UI CardContent

In the React Material-UI framework, I am working with a CardContent component that looks like this: <CardContent className={classes.cardContent}> <Typography component="p" className={classes.title} variant="title"> {this.props.post.title ...

Ways to modify the text of an HTML element when hovering over it

One of my elements contains the text &times; within a <span>. Is there a way to change this symbol to something else, like &infin;, when hovered over? <span class="change-text">&times;</span> When the mouse hovers over it, I ...

After the form is successfully submitted, you can remove the required attribute

Upon clicking the submit button of a form, an input box is highlighted with a red border if empty. After successful jQuery AJAX form submission, a message "data submitted" is displayed and the form is reset causing all input fields to be highlighted in red ...

Tips for creating $http calls in AngularJS

Having some issues with my code, as I'm unsure of the correct placement for making an $http request to a local server. api.js var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); va ...

What are the reasons and methods for cleaning up components in React JavaScript?

While I comprehend the necessity of tidying up our components in React to avoid memory leaks (among other reasons), as well as knowing how to utilize comonentWillUnmount (which is outdated) and the useEffect hook, my burning question remains: what exactl ...

Incorporating a timer feature into the code for my memory game

Seeking the optimal method to incorporate a timer into my memory game. This game comprises numerous squares, and when the user successfully completes it, a modal appears congratulating them on their win and providing an option to restart the game. The obj ...

The combination of Node.js module.exports and shorthand ternary operators for conditional statements

Can you explain the purpose of this line 'undefined' != typeof User ? User : module.exports and why is everything enclosed within (function(){})? I am having trouble understanding its significance. This code snippet is extracted from a library f ...

Tribal Code Typescript Compiler

Typescript is a great alternative to Javascript in my opinion, but it bothers me that it requires node.js as a dependency. Additionally, I find it frustrating that there seems to be only one compiler available for this language, and it's self-hosted. ...

Load images easily using jQuery

I am experiencing a small problem. I am attempting to display an image, but it doesn't seem to be correct. Although I am able to retrieve the data of the image, my goal is just to display it instead. What could be causing this issue? var imageUrl = ...

JavaScript nested function scope loss issue is being faced

Could someone provide an explanation of the scope binding in this code snippet? window.name = "window"; object = { name: "object", method: function() { nestedMethod: function() { console.log(this.name); ...

Tips on hiding specific table rows in two separate tables based on the chosen option from a dropdown menu

How do I hide table rows based on dropdown selection? The first table has a dropdown with two options: Current State and Future State. If I select Current State, I want to show or hide specific rows in the 2nd and 3rd tables. I am using IDs for these row ...

Was not able to capture the reaction from the Angular file upload

I've been attempting to upload a single file using the POST Method and REST Calling to the server. Despite successfully uploading the module with the code below, I encounter an error afterwards. Is there anyone who can lend assistance in troubleshooti ...

Which Angular component, directive, or pipe would be best suited for creating dynamic HTML content similar to this?

(I am transitioning from React to Angular, so please bear with me if my question has a hint of React influence.) I am in need of developing an Angular component that can accept a string along with a list of terms within that string for displaying tooltips ...

Is it possible to integrate two calendars into the `DatePicker` component of MUI?

The <DateRangePicker/> component from MUI has a prop called calendars which determines the number of calendars displayed inside the component popup. Here is an example: If the calendars prop has a value of "3", it will look like this: https://i.sta ...

Utilize the ng2-select component to incorporate multiple instances within a single webpage

Can someone help me figure out how to use two ng2-select components in my modal? I've checked out the documentation, but it doesn't provide any information on using more than one select. I'm not sure how to capture the selected values of ea ...

How can I retrieve the initial truthy value in JavaScript/NextJS for assigning to a property?

Within my NextJS project developed with JavaScript, I am seeking a way to assign a value to a property on a local object dynamically. const localItem = { name: <<value to be set goes here>> }; Handling the data used for setting the property ...

How can you retrieve a value in NodeJS Promise (Q) even when the promise fails?

As I dive into the world of promises in my NodeJS projects, I encountered a challenging situation. Despite reading the Promises/A+ spec and conducting extensive searches online, I struggled to find an elegant solution for accessing a value generated within ...

What is the advantage of utilizing AngularJs .constant() over simply declaring a JavaScript const variable?

Currently, I am involved in a project using AngularJS where we have implemented a .constant() provider to define some fundamental details that are utilized throughout the entire project. An example of this would be specifying a cookie name like so: .const ...

Add a parameter within a loop using JavaScript

I am currently working on a function with a parameter called menu. removeChildCheck:function(menu){ let removeArrayValues = []; for(var i=0; i < this.checkbox.menu.length; i++){ removeArrayValues.push(this.checkbox.menu[i].value); ...

Show session in HTML using ng-click after reloading the page

I am currently using the express-session package to store product prices in my application. Everything seems to be functioning correctly, however I am encountering an issue when trying to display the session data in HTML. For example, if there are 2 produc ...