Search code examples
functionfont-awesomeinnerhtmlgetelementbyid

Function change text does not work if I add font awesome


This is my function that takes the id from my button and changes the text:

var modal_button_update = document.getElementById("modal_button_text");
if (modal_button_update.innerHTML === "Add") { modal_button_update.innerHTML = "Update"; } 

It's working fine with this button (Add becomes Update)

<button type="button" class="btn btn-primary save_button add_group" id="modal_button_text">Add</button>

But for some reason it does not change anymore if I try to add a font awesome icon:

<button type="button" class="btn btn-primary save_button add_group" id="modal_button_text"><i class="fas fa-save" aria-hidden="true"></i>Add</button>

What could be the cause?


Solution

  • I ran your code. It seems the problem is that you are checking if your modal_button_update button's innerHTML is equal to Add. The original button:

    <button type="button" class="btn btn-primary save_button add_group" id="modal_button_text">Add</button>
    

    works because the innerHTML of your modal_button_update is exactly 'Add', but your modified modal_button_update: <button type="button" class="btn btn-primary save_button add_group" id="modal_button_text"><i class="fas fa-save" aria-hidden="true"></i>Add</button> does not work because the innerHTML is <i class="fas fa-save" aria-hidden="true"></i>&gt;Add which is not equal (===) to 'Add'.

    Here's three different ways I chose to solve this issue:

    1. Remove the <i class="fas fa-save" aria-hidden="true"> element and place the font-awesome icon inside the button class like: <button type="button" class="btn btn-primary save_button add_group fas fa-save" id="modal_button_text">Add</button> `
    2. Alter your Javascript to look something like: var modal_button_update = document.getElementById("modal_button_text"); if (modal_button_update.innerHTML.includes("Add")) { modal_button_update.innerHTML = "Update"; } Here the button checks to see if the innerHTML contains 'Add'.
    3. Keeping the font-awesome icon: In the two solutions above, your Javascript code will strip the button element of the font-awesome class when successfully changing the innerHTML to 'Update'. It is, imo, easier to use jQuery to alter the value of the button to solve this issue like:

    ---HTML---

                        <button type="button" class="btn btn-primary save_button add_group" id="modal_button_text"><i class="fas fa-save" aria-hidden="true"></i>Add</button>
    

    ---Javascript--

    if ($('#modal_button_text').html().includes("Add")) {
        $('#modal_button_text').html("Update");
    }