Manipulating the DOM by nesting an icon within a button element in HTML

Currently working on my todo list project and I have a question about using innerHTML. I'm curious if I can include an icon inside of a button tag like this:

btn.innerHTML = '<i class="fas fa-times fa-lg"></i>';

So, would that result in

<button><i class="fas fa-times fa-lg"></i></button>
?

Can someone explain the difference between the code above and the one below?

btn.innerHTML += '<i class="fas fa-times fa-lg"></i>';

Answer №1

To start, simply swap out the current content within the button for a fresh new icon

For example, if your button is labeled "click", this text would seamlessly transition to be represented by the newly added graphic symbol

In another scenario, an additional icon can be inserted immediately after the existing text "click"

Answer №2

btn.innerHTML = '<i class="fas fa-times fa-lg"></i>';

This particular code line will set the innerHTML of the btn.

btn.innerHTML += '<i class="fas fa-times fa-lg"></i>';

On the other hand, this code line will add

<i class="fas fa-times fa-lg"></i>
to the existing content inside btn. However, if btn is initially empty, it will produce the same result as
btn.innerHTML = '<i class="fas fa-times fa-lg"></i>';

For a simple demo, refer to the following:

var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
var btn3 = document.getElementById("btn3");

btn1.innerHTML = '<i class="fas fa-times fa-lg"></i>';
btn2.innerHTML += '<i class="fas fa-times fa-lg"></i>';
btn3.innerHTML += '<i class="fas fa-times fa-lg"></i>';
<body>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" rel="stylesheet"/>
  <button id="btn1" >Something Inside</button>
  <button id="btn2" >Something Inside</button>
  <button id="btn3" ></button>
<body>

Answer №3

It's important to grasp the distinction between the two assignment statements

var name = (equals) sets the value to whatever you want

var name = "blaqkippah"
console.log(name)
blaqkippah

var age = 23
console.log(age)
23

(since variable name has already been declared, there is no need to declare it again with the var keyword)

var name = "blaqkippah"
console.log(name)
blaqkippah

The use of += in conjunction with strings involves joining them together. It provides a more concise way of writing code

name = name + "blah"

name += "deemyBoy"
console.log(name)
blaqkippahdeemyBoy // no space inserted as I wrote += "deemyBoy" not += " deemyBoy" 
ie. when joining 2 strings using += (or any other method) you have to manually add a 
space

var b = 'banana'
b
"banana"
b += ' apple'
"banana apple"
b
"banana apple"
b = 'apple'
b
"apple"

Numbers behave differently with += acting as the plus/addition operator, adding to what's already stored in b (with numbers you can also do -= (minus), *= (multiply) and /= (divide)

b = 2
console.log(b)
2
b += 3
console.log(b)
5
b = 4
console.log(b)
4

An example using minus:

b-=3
console.log(b)
1

An example using divide:

b /= 2
console.log(b)
0.5

An example using multiply:

b *= 50
console.log(b)
25

Returning to your question, I've utilized a JavaScript object so that innerHTML becomes a property on the object, allowing you to easily track the changing values in the console.logs

var btn = {} // declare empty JS object
undefined

btn.innerHTML = '<i class="fas fa-times fa-lg"></i>'; // assign value
console.log(btn)
{innerHTML: "<i class="fas fa-times fa-lg"></i>"}
btn.innerHTML += '<i class="fas fa-times fa-lg"></i>';
console.log(btn);
{innerHTML: "<i class="fas fa-times fa-lg"></i><i class="fas fa-times fa-lg"></i>"}
btn.innerHTML = '<i class="fas fa-times fa-lg">go back to original</i>';
console.log(btn);
{innerHTML: "<i class="fas fa-times fa-lg">go back to original</i>"}

This should provide a more comprehensive explanation for you

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

Order of callback execution in jQuery's ready function

When two JavaScript functions on a page need to be called once the document load is complete, is there a possibility that one function could be executed before the other, or will it always be the same order? For example, using jQuery with the following co ...

Is it possible to utilize CSS rules for a non-existent div within CSS?

Can this be achieved using CSS? If .div1 is not present, enforce the following rule: .div2{ property: value; } For example, <div class="div1"> ... </div> <div class="div2"> <!-- it exists, so no action needed --> </div& ...

Can JavaScript event listeners be compelled to trigger in a specific sequence?

Is there a way in JavaScript to receive notification or execute a callback function once an event has completed its propagation? Put differently, is it possible to 'prioritize' an event and ensure that it gets triggered after all other event lis ...

What is the best way to retrieve the data from a specific section when a checkbox is selected in Angular 2?

When I select a checkbox for any section and then click the submit button, I want to display the details of that section in the console. Can someone assist me with this? **Stackblitz link:** : https://stackblitz.com/edit/angular-q7y8k1?file=src%2Fapp%2Fa ...

Tips for effectively placing a page scope block using BEM

Here is the current structure of my header. The page component is assumed to be the root. Currently, the geometry of the social-links block is being controlled by the header__social-links mix (positioned absolutely relative to the header). How can I prop ...

Converting Excel values to Exponential format using Python

I'm struggling to find a solution for extracting the Invoice Number in Python from an Excel sheet without turning it into exponential form. Expected Value: 8000030910 Result: 8.00002e+09 Python Result Excel sheet d1.append(sheet.cell_value(j,0)) ...

Immersive pop-up interface displaying a variety of embedded videos simultaneously

I am a beginner in JavaScript and I came across a CodePen that does exactly what I need, but it currently only works for one embedded video. What I aim to achieve is similar functionality, but with 6 videos. (function ($) { 'use strict'; ...

Replace the image source with a list of images

I am looking to create a dynamic image list using either an array or an HTML list. When I hover over an image, it should change one by one with a fade or slide effect, and revert back to the default images when I hover out. Question 1: What type of list s ...

Unexpected bug encountered while implementing redux

I received a warning from eslint while working with create-react-app. ./src/components/auth.js Line 24: Unexpected labeled statement no-labels Line 24: 'authenticated:' is defined but never used ...

Using getJSON to return key/value pair from local host URL in JSFiddle - A step-by-step guide

After following a tutorial on building an API using Python, Flask, SQLite, and SQLAlchemy, I have successfully tested the connection by hitting the localhost address in my browser. Now, I am curious if it is possible to test this connection and see the des ...

Guide to retrieving the previous URL in Angular 2 using Observables

Can someone help me retrieve my previous URL? Below is the code snippet I am working with: prev2() { Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)). then(function(v){ console.log('Previous ' ...

Avoid showing duplicate values in the optgroup selection

Show the database value in the optgroup option. If the value of the parsing controller is equal to the option's value, do not display it within the HTML tag. Value of the parsing controller: {{$getData->status}} This is how my view blade looks: ...

Encountered an issue while attempting to write to SQLite, error code 6 is

I'm working on a project that involves writing to a SQLite Database from a cross-platform app built with AngularJS, Monaca, and Onsen UI. Within my app, there's a view where users input their username and password. I store these details in a Ser ...

Is it possible for me to transform this code into a useful helper function?

I am looking to optimize this conditional code by converting it into a helper function using a switch statement instead of multiple if statements. How can I achieve this in a separate file and then import it back into my component seamlessly? import { ...

Adjust the content within an HTML div by utilizing AngularJS

Snippet of AngularJs code to display different content based on selection: <select> <option value="0">--Select--</option> <option value="1">Individual</option> <option value="2"> ...

Is there a way to automatically update the URL to include $_GET['data'] (media.php?data=123) when a selection is made from a dropdown list?

I'm currently working on a project that involves a website in PHP and a MySQL database. I have successfully linked the two together, and now I have a combobox filled with data from the database. Below is my script for handling the selection: <scr ...

What is the method for utilizing the onmouseover function to emphasize a specific part of an SVG graphic?

I am attempting to create an interactive SVG map of Europe. Each country is represented by a path element, and I want the opacity of a country to change to 0.5 when it is hovered over. Despite trying to define a JavaScript function for this purpose, noth ...

Tips on preventing duplication of APIs when retrieving data using nextjs

In my code, I have a function that can be called either from server-side rendering or client side: export const getData = async (): Promise<any> => { const response = await fetch(`/data`, { method: 'GET', headers: CONTENT_TYPE_ ...

Having trouble retrieving cookie in route.ts with NextJS

Recently, I encountered an issue while using the NextJS App Router. When attempting to retrieve the token from cookies in my api route, it seems to return nothing. /app/api/profile/route.ts import { NextResponse } from "next/server"; import { co ...

The validation of the form does not seem to be functioning properly when the 'required' rule is used

I have implemented the Required form validation in my input fields to prevent submission with empty data. However, it seems like my required validation is not functioning as expected. function AddCar() { const [chasis, setChasis] = useState("" ...