Home > Software design >  changing text content using dom manipulation
changing text content using dom manipulation

Time:10-04

i have written some javascript code that i feel should change the inner text of a html button onclick but it doesn't seem to work as intended. i have looked for syntax errors but cant seem to find any, have put the onclick function in various place . what am i missing out on?

const clicked = false;
function toggle(){
    if(!clicked){
        clicked = true;
        document.getElementById("readbtn").innerHTML = "Not read";
    }
    else{
        clicked = false;
        document.getElementById("readbtn").innerHTML = "Read";
    }
}
.btn.delbtn{
    background-color: #990026;
    
}

.delbtn:hover{
    background-color: #ec0e46;
    transition: 0.7s;
}

.btn{
    border-radius: 4px;
    font-weight: 1000;
    font-size: 1rem;
    /* padding: 5px; */
    background-color: #465c6b;
    color: aliceblue;
    border: none;
    letter-spacing: 0.7px;
    padding: 10px 20px 10px 20px;
   
}

.rdbtn:hover{
    cursor: pointer;
    background-color: #779bb3;
    transition: 0.7s;
}
 <table>
        <thead>
            <tr>
                <td>Name</td>
                <td>Author</td>
                <td>Status</td>
                <td>      </td>
            </tr>
        </thead>
       
        <tbody>
            <tr>
                <td>The Hobbit</td>
                <td>J.R.R Tolkien</td>
                <td><button id="readbtn"  onclick="toggle()">Read</button></td>
                <td><button >Delete</button></td>
            </tr>
        </tbody>
    </table>

CodePudding user response:

Change const clicked = false; to var clicked = false;

var clicked = false;
function toggle(){
    if(!clicked){
        clicked = true;
        document.getElementById("readbtn").innerHTML = "Not read";
    }
    else{
        clicked = false;
        document.getElementById("readbtn").innerHTML = "Read";
    }
}
.btn.delbtn{
    background-color: #990026;
    
}

.delbtn:hover{
    background-color: #ec0e46;
    transition: 0.7s;
}

.btn{
    border-radius: 4px;
    font-weight: 1000;
    font-size: 1rem;
    /* padding: 5px; */
    background-color: #465c6b;
    color: aliceblue;
    border: none;
    letter-spacing: 0.7px;
    padding: 10px 20px 10px 20px;
   
}

.rdbtn:hover{
    cursor: pointer;
    background-color: #779bb3;
    transition: 0.7s;
}
 <table>
        <thead>
            <tr>
                <td>Name</td>
                <td>Author</td>
                <td>Status</td>
                <td>      </td>
            </tr>
        </thead>
       
        <tbody>
            <tr>
                <td>The Hobbit</td>
                <td>J.R.R Tolkien</td>
                <td><button id="readbtn"  onclick="toggle()">Read</button></td>
                <td><button >Delete</button></td>
            </tr>
        </tbody>
    </table>

  • Related