The CSS formatting is not being properly applied within the innerHTML

I have a scenario where I am trying to display a Bootstrap card using innerHTML in my TS file, but the styles are not being applied to this content. I suspect that the issue might be because the styles are loaded before the component displays the card, causing them not to work properly. Does anyone have any advice on how to address this problem? My project is built on Angular 12.

Here is an excerpt of my TS code:

constructor(private _route: ActivatedRoute, private router: Router) {

    // News data
    this.noticias = [
      {
        id: '1',
        vTitulo: 'Convención anual de la Asociación Mexicana de Semilleros (AMSAC)',
        dFecha: 'DIC 2021'
      },
      {...}
    ]

    // Logic for displaying news cards with filtered search functionality
    $.when($.ready).then(() => {
      
      const noticiasList = document.getElementById('noticiasList');

      let displayNoticias = (noticias: any[]) => {
        // Generating HTML for each news item
        const htmlString = noticias
          .map((noticia) => {
            return `
              <div class="card cardNoticias">
                {...}
              </div>  
            `
          })
          .join('');
        
        // Rendering the news items
        if(noticiasList) noticiasList.innerHTML = htmlString;  
      }

      // Filtered search based on user input
      let filtradoNoticias = this.noticias.filter((noticia) => {
        return (
          noticia.vTitulo.toLowerCase().includes(this.busqueda.toLowerCase())
        );
      })
      displayNoticias(filtradoNoticias); 
      
     }) 
  }

This is where I'm inserting the innerHTML:

<div class="col-lg-12 ms-2 ps-lg-3 pe-lg-2 mt-2 mt-xl-2 mb-5">
    <h1>NOTICIAS ENCONTRADAS</h1>
    <div id="noticiasList">
      
    </div>
  </div>

And here are the CSS styles I want to apply to the news cards:

.noticiasList .cardNoticias{ 
  background-color: gray; 
}

.noticiasList .cardNoticias .card-body-noticiasList {
  width: 100%;
  padding-right: 30px;
}

.fecha {
  {...}
}

In essence, the TypeScript code filters news titles based on user input and dynamically displays the relevant news cards.

Answer №1

noticiasList is the identifier of the element, not a class associated with it.

To style that div in CSS, you should utilize the # selector (which is used for IDs).

Therefore, your CSS code snippet would look like this:

#noticiasList .cardNoticias{ 
  background-color: gray; 
}

#noticiasList .cardNoticias .card-body-noticiasList {
  width: 100%;
  padding-right: 30px;
}

.fecha {
  background-color: lightgray;
  margin-right: 1px;
  text-align: center;
  width: 30px;
}

For further guidance, refer to https://www.w3schools.com/cssref/sel_id.asp

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

"Encountering a 'Module Not Found' error in Node.js after

Recently, I added a node-module to my project using the command: npm install typescript --save-dev However, when I tried running: tsc Windows displayed an error message indicating that "tsc" is an unknown command. Strangely, this issue does not occur o ...

Fetching data from React Router v6 Navigate

When I navigate to a new route, I am encountering an issue with passing state data in TypeScript. The error message says: Property 'email' does not exist on type 'State'." The parent functional component looks like this: naviga ...

What is the best way to apply a filter to an array of objects nested within another object in JavaScript?

I encountered an issue with one of the API responses, The response I received is as follows: [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyNa ...

Tips for compressing an image in a React application with the help of react-dropzone

I have integrated the react dropzone package into my Next JS app and I am looking to add automatic image compression feature. After receiving the images, I converted the blob/preview into a file reader. Then, I utilized the compressorjs package for compre ...

Guide on importing a markdown file (.md) into a TypeScript project

I've been attempting to import readme files in TypeScript, but I keep encountering the error message "module not found." Here is my TypeScript code: import * as readme from "./README.md"; // I'm receiving an error saying module not found I als ...

What is the best way to ensure that my website's elements adjust automatically to different screen sizes?

Recently, I encountered a small snippet of HTML code with the main focus being an h2 element. #top-warning{ justify-content: center !important; display: flex; width: 100%; margin-top: 5vw; letter-spacing: 3px; font-family: "Penguin Regular ...

Adding a characteristic to every item in an array of objects

Currently, I am utilizing Node.js along with Mongoose to interact with a MongoDB database and retrieve an array of objects from a specific collection. However, my aim is to add an additional property to each of these retrieved objects. Below, you can see t ...

A step-by-step guide on modifying the box-shadow color using jquery

I have developed some JavaScript code that adjusts the box-shadow of buttons to be a darker version of their background color. This allows users to dynamically change the button background colors. The current code successfully changes the box shadow based ...

How can I ensure that Chakra UI MenuList items are always visible on the screen?

Currently, I am utilizing Chakra UI to design a menu and here is what I have so far: <Menu> <MenuButton>hover over this</MenuButton> <MenuList> <Flex>To show/hide this</Flex> </MenuList> </ ...

Issue with importing RxJS in an Angular 5 project

Help needed! I can't find Observable, how do I use rxjs on http? Can someone please provide guidance? import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { IEmployee } from '. ...

Dealing with null route parameters for Express applications

I am facing a challenge in handling an empty route parameter when a path is not specified. My intention is to return a new date if the route parameter is empty. However, the server's response so far is: Cannot GET /api/timestamp/ app.get("/api/timest ...

Unlimited webpage scrolling downward

Recently, I was given a project to enhance a webpage and encountered an unusual issue. When the screen resolution drops below 900px (such as on small laptops and tablets) and you reach the bottom of the page, you can continue scrolling endlessly after seei ...

Utilize the client's IP address as a cookie in order to recognize return visits and showcase a special message following the initial visit

First of all, a big thank you to anyone who can help resolve this issue. I apologize if this has been asked before (I couldn't find it anywhere, so I decided to post a new question). The main problem I am facing is getting my webpage to show an alert ...

Boosting the specificity of Material UI override styles

I came across a question about Material UI Overriding styles with increased specificity that seemed related to my issue, but I couldn't apply the solution to my problem. My problem involves a vertical Slider with marks, and I am trying to remove the ...

Adjusting the size of an image based on the size of the window

I'm currently working on my first website project. I have successfully implemented a large image banner, however, I am facing an issue with setting its height. Whenever I try to adjust the height using percentage values, the banner disappears. My goal ...

li tag style

I need to insert a check mark inside the <li> tag on the right side. How can I do this? The check mark looks like this: For example: http://jsfiddle.net/HpVcy/ ul li{ padding: 3px 10px 3px 10px; background:url(http://img4up.com/up2/730897458613759 ...

Click on every sublist within the unordered list items

In this coding example, there are multiple ul and li elements. Upon running the code, you will observe that test1 is positioned 10px from the left as it is nested within TEster, but achieving an additional 10px offset for Tester2 appears to be a challenge ...

CSS: The Drop Down menu suddenly vanishes every time I attempt to select an item from the visible list

I'm facing an issue with my dropdown menu that I can't seem to resolve. Whenever I hover over the menu, it disappears before I can even click on any items. <ul id="menu"> <li><a href="#title">Home</a></li> ...

Warning: Knex was unable to acquire a connection due to a timeout, resulting in an UnhandledPromiseRejectionWarning

I'm having trouble connecting my Telegram bot to the database using knex. I am working with MySQL, and I have already created the database and tables which are visible on the /phpMyAdmin page. The credentials used for accessing the database in my code ...

What is the best method to loop through this object with JavaScript?

Suppose I have the following data: let testData = { 'numGroup1': [[(1, 2, 3, 4, 5), (5, 6, 7, 8, 9)]], 'numGroup2': [[(10, 11, 12, 13, 14), (15, 16, 17, 18, 19)]] }; What is the best approach to iterate through this data using Jav ...