Home > Net >  Javascript setAttribute is not working to update attribute's value
Javascript setAttribute is not working to update attribute's value

Time:11-12

This is my code.

var hitButton = document.querySelector('.btn-hit');
var scoreResults = document.querySelectorAll(".flex-blackjack-row-1 h3");
var scores = document.querySelector(".flex-blackjack-row-1 span");

const config = {childList: true};

const bustedMessage = document.createElement('h2');
bustedMessage.textContent = 'BUSTED!';

const busted = function (mutationList, observer){
    if (parseInt(scores.textContent) > 21) {
        console.log(scores.textContent)
        scoreResults[0].before(bustedMessage);
        hitButton.setAttribute('disabled', 'true');
    }
}

const observer = new MutationObserver(busted);
observer.observe(scores, config);

In that callback function named "busted", I'm adding an attribute to "hitButton". But when I try to update it like this in another function

hitButton.setAttribute('disabled', 'false');

it is not being updated.

But I can remove that attribute using

hitButton.removeAttribute('disabled');

Removing that attribute is doing what I want to do. But now I need to know, why can not I update it instead of removing?

CodePudding user response:

Because, these attributes in HTML tags are just boolean attributes. Say for e.g., if "disabled" attribute is present, it tells the browser to disable it regardless of the value you are setting to it.

"checked", "disabled", "selected", "muted", "autoplay", "loop", "controls" are some of the boolean attributes in HTML.

Google "Boolean attributes in HTML". You will learn more about it. Hope it answers your question.

  • Related