Document.querySelector() doesn't work with bootstrap css

Viewed 715

HTML

<html lang="en">

<head>

    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="firstapp.js"></script>
</head>

<body>

    <div id="buttons">
        <h1>Hello</h1>
        <h2>0</h2>
        <button class="btn btn-primary" type="submit">Hello</button>
        <button class="button2">count </button>
    </div>

</body>

</html>

Javascript

let x = 0

function counter() {
    x++;
    document.querySelector('h2').innerHTML = x;
    if (x % 10 === 0) {
        alert(`counter is now ${x}`);

    }
}
document.addEventListener("DOMContentLoaded", function() {
    document.querySelector('.button2').onclick = counter; //This statement is for counter function 
    document.querySelector('.btn btn-primary').onclick = function() { //This is Hello Function 
        let heading1 = document.querySelector('h1');

        if (heading1.innerHTML === "Hello!!") {
            heading1.innerHTML = "Goodbye!!";
            //document.querySelector('.btn btn-outline-secondary').innerHTML = 'goodbye';
        } else {
            heading1.innerHTML = "Hello!!";
            //document.querySelector('.btn btn-outline-secondary').innerHTML = 'Hello!!';
        }


    };
})

When I Document.queryselector with a local css file it works just fine but as soon as I link a bootstrap class the Java scropt doesn't recognize any bootstrap class and gives out an error " TypeError: Cannot set property 'onclick' of null at HTMLDocument. "

2 Answers

In JavaScript, elements are selected with CSS selectors, not HTML syntax.
Change

document.querySelector('.btn btn-primary')

to

document.querySelector('.btn.btn-primary')

to denote an element with two class names. Do similarly with the rest by changing spaces to dots.

in primay button add new class for ex 'pbtn' and replace this document.querySelector('.btn btn-primary')

with this

document.querySelector('.btn.btn-primary')

Related