I am facing issues with the CSS in my EJS file when it is being rendered within an if statement

Having trouble applying CSS to this EJS file, no matter what styling I use. Here's the code snippet:

itemEdit.ejs

<%- include("partials/header.ejs", {title: ` - Items`, body_id: `items`} )%>
<%- include("partials/navbar.ejs", {bg: `dark`})%>

<div class="edit-container">
    <div class="row">
        <h1>Edit item</h1>
        <a href="/items">
            <<<-Back to items page</a>

    <form action="/itemEdit/item-edit/<%= item._id%>" method="post">
        <input type="text" name="name" placeholder="enter item name">
        <input type="text" name="description" placeholder="enter item description">
        <button class="btn btn-primary" type="submit">Submit</button>
    </form>
</div>

<%- include("partials/footer.ejs")%>

index.ejs

app.get('/itemEdit/:id', isLoggedIn, (req, res) => {
    // Query for session user object
    User.findById({ _id: req.user._id },
        (err, doc) => {
            if (err) { console.log(err); }
            else {
                const { userInventory } = doc

                for (let i = 0; i < userInventory.length; i++) {
                    if (userInventory[i]._id == req.params.id) {
                        res.render('itemEdit.ejs', {
                            item: userInventory[i], // Item object
                            user: doc // Session user object
                        })
                    }
                }
            }
        })
})

Adding CSS but it doesn't apply:

style.css

.edit-container {
    background-color: red;
}

Even after adding red background, no change seen. CSS is loaded from header.ejs and works on all other EJS files except this one. Could it be due to being inside an IF statement hindering CSS application? Even footer doesn't display properly compared to other EJS pages.

Any assistance appreciated!


UPDATE

Noticing the app treating itemEdit.ejs as a folder in the console. See screenshot: console. Surprised by this behavior, since it's just a simple EJS file. What could be causing this?

Answer №1

If you want to streamline the process, consider integrating express as a dependency.

To do this, run the following command: $npm install express

Create a folder called "public" within your project directory. Inside the public folder, you can organize your css files.

Next, update your index.ejs file with the following code:

const express = require("express");

const app = express();

app.use(express.static("public")); 

This setup grants EJS the ability to fetch static files from the public directory, eliminating the need for internal css.

Answer №2

Have you experimented with this structure: href='/stylesheets/style.css'? Leaving out the '/' will result in searching in the relative path, leading to

'/itemEdit/stylesheet/style.css'

You can also verify the path of the requested file by accessing the debug window and navigating to the 'network' tab. Press F5 to refresh the page and you'll observe all files being loaded.

At this stage, you can select a specific file (such as style.css) and examine the complete path that the browser is utilizing to retrieve the file.

Answer №3

I encountered a similar issue and managed to trace it back to a specific line of code within the header partial file:

<link rel="stylesheet" href="css/styles.css">
. Even though my CSS was located in a public folder, I couldn't pinpoint the problem.

After experimenting with adding a forward slash like so:

<link rel="stylesheet" href="/css/styles.css">

This adjustment resolved the issue without impacting the remainder of the code. While I'm not entirely sure why this workaround worked, I plan on delving deeper into the topic. Hopefully, this explanation proves helpful!

Answer №4

There was a similar issue that I encountered, specifically when the route URL contained a dynamic variable. For instance, in your scenario '/itemEdit/:id', 'id' serves as the variable. Strangely, the browser interprets 'itemEdit' as a distinct folder and 'id' as a file within that folder.

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

In IE9/10, the absolutely positioned pseudo element within a table cell does not fully overlay its parent

My layout includes nested div elements displayed as a table and table-cell, with each cell containing an absolutely positioned :before element that covers the entire cell. While this setup works perfectly in most browsers, I am facing an issue in IE9, 10, ...

Encountering difficulties accessing Node.JS Sessions

Hey there, I am currently working on integrating an angular application with Node.js as the backend. I have set up sessions in Angular JS and created my own factory for managing this. Additionally, I am utilizing socket.io in my Node.js server and handling ...

The font appears bolder in Chrome once the CSS animation has finished

My CSS animation is causing some unexpected behavior on page load. Once the animation completes, the text suddenly appears thicker than intended, especially when it's a specific shade of red. Curiously, this strange "popping" effect only occurs with ...

Avoid incorporating unicode characters in Angular 4

How can I prevent users from using unicode characters in a text field in my front-end developed with Angular 4 framework? For example: ½ -> U+00BD ('onehalf') ...

Discover the best practices for utilizing CSS selectors reliably in puppeteer

For a project, I am currently working on customizing a puppeteer script that is able to play a song from Soundcloud and record it. The main goal is to utilize a CSS selector to display the duration of the song as well. I am encountering difficulties with g ...

What is the best way to ensure that a <label> remains vertically aligned with its <form>?

I'm struggling to incorporate their suggestions into my design. How can I align my label to the left of my input field on the same line? Also, I'm a beginner in coding so please excuse any mistakes in my code: body { background-color: #f5f ...

What is the best way to remove documents from a collection when it reaches a certain limit?

Can I use a Mongoose command to automatically delete records in a collection if they exceed a certain number? I'm looking for a more efficient way than manually querying, sorting by date, and parsing each document individually. ...

When sending a response using res.send, it is not possible to include all properties of

I'm working with an API controller method that looks like this: let object = { "key1": "value1", "key2": "value2", "arrayKey": [ { "arrKey": "arrValue", "arrKey1": 1 } ] } export const foo = ...

Accessing local filestream with alternative source as backup

My approach to file management involves storing files in Amazon S3 while also maintaining a local file cache. To optimize efficiency, I want to prioritize checking the cache before accessing any file. I aim to utilize promises and streams in my implementat ...

jQuery fails to register a click event on a child element

I've designed a div element to serve as a contact list, containing other divs within it. I'm attempting to set up a click handler on each list item (inner div) but the click event is not being triggered. $(".contact").on("click", function() { ...

Utilize socket communication with node.js to monitor and identify user

I'm attempting to find a method to unsubscribe from a Redis channel when the user navigates to another page within our website. I have attempted to detect a disconnect socket event when the user clicks on a link, but unfortunately, the event is never ...

What impact does incorporating a new test case have on code coverage in Jest?

I recently encountered an unexpected situation while working on a Jest test suite. Despite not making any changes to the codebase, I simply added a new test. Originally: mylibrary.js | 95.65 | 89.66 | 100 | 95.65 | 54-56,84 ------------ ...

Text in React Native exceeding one line is causing it to extend beyond the screen boundaries

I am having trouble displaying the last messages in my simple contact list as the text is getting cut off the screen. Below is the code I am using: (the readableTimestamp should be positioned behind the text.) View style={{ fontSize: 16, backgro ...

Apollo Server with Express is displaying "Unable to access /" instead of the Graphql playground

Recently, I've been working on implementing Apollo GraphQL in my server.js and schema.js files by following the tutorial provided in the official documentation here Here is a snippet from my server.js file: import apollo from "apollo-server-expr ...

Present the value of an object within an array in an HTML format

I have organized an array containing information about different video games: let games = [{ title: 'Fortnite', price: 20, img: "./assets/images/Fortnite.jpg" }, { title: 'Valorant', price: 0, img: "./asse ...

Interacting with Arrays in Node.js based on User Input

Can anyone please help me figure out what I'm doing wrong? I'm trying to create a discord command: C!send quote (number) (username) that will allow me to select a specific quote from a list and send it as a message. msg.channel.send(`${quotes.quo ...

What is the purpose of running "npm install" if the "node_modules" directory already exists?

When "npm install" is run on a project directory containing both a "package.json" file and a "node_modules" directory, what impact does it have? Does it replace the current modules with newer versions? Does it update them, or does it have no effect at all ...

Create an HTML selection element based on the value selected in the previous element using jQuery

I have an issue with generating a third HTML select element based on the selection of a first HTML select element and the use of an AJAX function. The process works correctly for the second select element, but when I try to generate the third select elemen ...

Updating Button Text Upon Click

I am looking to create a webpage filled with riddles. After each riddle, there will be an answer button that, when clicked, reveals the answer. Clicking the button again should hide the answer. I attempted to implement this functionality using Javascript, ...

A step-by-step guide on implementing the populate method in a project using React and Node.js

I have two collections in my database called "users" and "forms." Each user has a table of forms. I utilized the populate method to achieve this, and it works. This is the model for the user: const Schema = mongoose.Schema const UserSchema = new Sch ...