Using Document.querySelector() in combination with Bootstrap CSS may lead to unexpected results

CSS & 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!!';
        }


    };
})

Issue with Bootstrap Classes in JavaScript

I encountered an issue where my document.queryselector was unable to recognize any bootstrap classes when linked to a local CSS file. This resulted in the error message "TypeError: Cannot set property 'onclick' of null at HTMLDocument." It seems like there might be a conflict between Bootstrap and my JavaScript code causing this problem.

Answer №1

In JavaScript, elements are usually targeted using CSS selectors rather than HTML syntax.
Modify the following code snippet:

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

to:

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

This change is necessary to indicate an element with multiple class names. Apply the same principle by replacing spaces with dots for other elements as well.

Answer №2

When adding a new class to the primary button, make sure to include it as 'pbtn' and replace the current code

from:

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

to:

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

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

Symfony 2 lacks the ability to automatically create the web/bundle/framework structure

I encountered a major issue with Symfony. After installing Symfony 2.7.5 via the command line: $ symfony new my_project The problem arose in the generated project directory: /web/bundle In this folder, I found two empty files (not directories!) named fr ...

What is the issue with retrieving HTML from an iframe in Internet Explorer when the contents are

Here is the script I used to generate an iframe: Ifrm = document.createElement("IFRAME"); document.body.appendChild(Ifrm); IfrmBod = $(Ifrm).contents().find('body'); IfrmBod.append('<p>Test</p>'); The jQuery function for a ...

The utilization of CSS within Flask can sometimes lead to a state

Struggling with a python Flask issue here and could really use some help. My CSS is completely out of whack and not displaying correctly at all. Despite setting everything up in static_files and seeing only a 304 code in the terminal, even when trying new ...

The descendant selector in CSS fails to apply changes to the element

I am struggling to modify the border of a specific descendant element and so far I have not been successful. Despite using the correct descendant selector in the HTML below, the style change is not taking effect. If anyone has any insights on what could be ...

Providing an image in a Django web application

I'm having trouble displaying an image on my Django web app. Despite placing the image in the static folder, and the hello.html in the templates folder, I'm still getting a broken image link. Below is the content of hello.html: {% load static %} ...

What is the most efficient way to clear the input field in Angularjs when the backspace or delete keys are pressed?

Is there a way to reset an input field with AngularJS when the backspace or delete keys are pressed? I've implemented this fantastic directive, and it's been working great, except for when the user uses the backspace or delete key to clear the f ...

Unexpected error encountered with node.js when attempting to run: npm run dev. A TypeError was thrown stating that require(...) is not

Working on my initial project, I have set up a database and am in the process of creating a login page. However, when trying to run it using 'npm run dev', an error is encountered (see below). I am unsure of what is causing this issue and how to ...

Utilizing the map function to incorporate numerous elements into the state

I'm struggling with 2 buttons, Single Component and Multiple Component. Upon clicking Multiple Component, my expectation is for it to add 3 components, but instead, it only adds 1. import React, { useState, useEffect } from "react"; import ...

Responsive Gallery Grid Slider with uniform height boxes

Looking to develop a responsive gallery grid slider with equal height boxes. For instance, at 650px wide or wider, display 3 columns and 2 rows. When the width is 550px or less, switch to 2 columns and 3 rows. If the width is 450px or less, go down to 1 ...

Creating a line break in a Vue.js confirmation dialog is a helpful feature that can be achieved with a

Is there a way to add a new line after the confirmation dialog question and insert a note below it? this.$dialog.confirm("Create Group","Would you like to create group "+ this.groupName +"?<br/>(NOTE: Selected project or empl ...

Is there a way to create a multi-page website simulation using jQuery?

My current project involves creating a single page website, but I am looking to give the illusion of a multi-page site by using CSS/jQuery to hide and reveal different sections when specific links in the navigation menu are clicked. Here is the code snipp ...

Best practices for defining module-wide constants in AngularJS

In my project, I have around 20 "modules" each with its own unique functionality but following the same structure. These modules are stored in separate files within their respective folders. For instance, the admin module is located in the modules/admin fo ...

Having trouble deleting multiple rows with ng-repeat in datatables

Having followed the instructions in this post, I quickly integrated it with jquery datatables. However, the functionality is not as expected. When attempting to delete rows, they do not get deleted. Furthermore, if I navigate to the next page and return, ...

Website automation can be simplified by utilizing the Webdriver.io pageObject pattern, which allows for element selectors

Currently, I am following a specific example to define elements within pageObjects using the ID selector... var Page = require('./page') var MyPage= Object.create(Page, { /** * defining elements */ firstName: { get: function ( ...

The action is undefined and cannot be read for the property type

Using the React+Redux framework, I encountered an error: https://i.sstatic.net/0yqjl.png During debugging, the server data successfully reached the state, but the action was empty: https://i.sstatic.net/41VgJ.png Highlighted below is a snippet of my co ...

Troubleshooting: Why is my console.log not working in JavaScript

Recently, I've been diving into the world of JavaScript, but for some reason, I can't seem to make console.log function properly. At the top of my HTML document in the head section, I added jQuery like this: <script type="text/javascript" sr ...

grab the destination URL from the embedded frame

Thank you for your attention. I am working with three iframes spread across different HTML documents. Here is how they are organized: In the file iframemain.html, there is: <iframe src="iframeparent.html" width="100%" height="600"> </iframe> ...

javascript calculate average based on user input array

There is a problem that I am trying to solve, but as a beginner it seems quite challenging. Here is the code I have written so far, however, when I run it only one window appears. Any advice or guidance would be greatly appreciated. var years = prompt(" ...

I'm confused why this code is functioning in JSFiddle but not on my HTML webpage

For the first time, I am encountering this issue. I am currently attempting to integrate this code into my application http://jsfiddle.net/TC6Gr/119/ My attempts include: Pasting all the jsfiddle code in a new page without my code, but it doesn't w ...

Percy snap shot test cannot be executed in Testcafe due to the error message: npm ERR! The script 'test:percy' is

For my initial test with percy snapshot, I used the command below: npm run test:percy Unfortunately, an error message appeared when running the command: xxx.xxx@LPG002572 TC-Visual % npm run test:percy npm ERR! missing script: test:percy npm ERR! A com ...