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

New design for UI grid: eliminate sorting menu and right-align column headers

I came across a question similar to this one My goal is to eliminate the dropdown menu from the column headers and align the text of the headers to the right. .ui-grid-header-cell { text-align: right; } However, my current attempts result in the disap ...

Issue with TypeScript: Error appears when importing express after running "npm i @types/express -D"

Struggling with adding the following line of code in an index.ts file: import express, { Application } from 'express'; Initially encountered an error with "from 'express'", so I ran npm i @types/express -D which fixed that is ...

Utilizing shared components across a Next.js application within a monorepo

Utilizing a monorepo to share types, DTOs, and other isomorphic app components from backend services (Nest.js) within the same mono repo has presented some challenges for me. In my setup, both the next.js app and nest.js app (which itself is a nest.js mono ...

Assist with JavaScript Programming

Can someone assist me in creating functionality for the "Show Picture" button to toggle the visibility of the picture when clicked? I've been trying to achieve this using an If/Else statement for a school project but have been struggling with it. Any ...

Evaluating Vue.js Watchers using Jasmine

I want to write a test for a VueJS watcher method, in order to verify if it's being called. The watcher method in my component is structured like this: watch: { value: (newValue, oldValue) => { if (newValue.Status === 'Completed') ...

Iterate over JSON elements beginning with a specific pattern

What is the best way to iterate through JSON objects that specifically start with a certain format? For example, if we have a JSON structure like this: { "END": true, "Lines": "End Reached", "term0": { "PrincipalTranslations": { // nest ...

Dart and external CSS and JS libraries and tools

As I prepare to dive into developing my very first web application, one technology that has caught my eye is Google Dart. The idea of using a new, innovative approach to web development excites me, and I am seriously considering utilizing it for my project ...

Alerting error message during Laravel array validation via ajax causes error to be thrown

Seeking assistance with validating arrays in Laravel using FormRequest validation <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class VendorStoreRoom extends FormRequest { /** * Dete ...

Executing the outer function from within the inner function of a different outer function

Imagine this scenario: function firstFunction() { console.log("This is the first function") } secondFunction() { thirdFunction() { //call firstFunction inside thirdFunction } } What is the way to invoke firstFunction from thirdFunction? ...

Tips for extracting information from Observable that is supplied with data from an external API

Beginner in the world of Reactive programming (and Angular). I’m eager to create my first data stream and receive something other than an error message in the console output :) Here is what I've attempted: export class AppComponent { requestS ...

Is it possible to refresh a table that is currently displayed in a model popup?

My code to reload a table or div inside a model popup continuously is not working as expected. Can you help me with this issue? I attempted to utilize ajax for this purpose but unfortunately, the code below is not updating chats (I am working on a chat ta ...

Demonstrating reactivity: updating an array property based on a window event

One example scenario involves setting specific elements to have an active class by assigning the property "active" as true (using v-bind:class). This property is modified within a foreach loop, after certain conditions are met, through the method "handleSc ...

By implementing a custom function within the router's "redirectTo" method, we can dynamically determine the destination for redirection, effectively avoiding Ahead-of-Time (A

By implementing a function to decide where the user should be directed when the site loads, I encounter the following challenge: { path : '', redirectTo: redirector(), pathMatch: 'full' } The redirector() function returns a rout ...

To determine if two constant objects share identical structures in TypeScript, you can compare their properties

There are two theme objects available: const lightMode = { background: "white", text: { primary: "dark", secondary: "darkgrey" }, } as const const darkMode = { background: "black", text: { prim ...

How can parameters be sent without using the .jshintrc file with the gulp-jshint package?

Currently in the process of transitioning a grunt project to a gulp project. In the existing gruntfile, there is a section for the jshint task that looks like this: jshint: { options: { trailing:true, evil:false, indent:4, ...

Conceal or reveal buttons using JavaScript

I am struggling with a function that is supposed to hide certain buttons and create a new button. When I click on the newly created button, it should make the previously hidden buttons visible again. However, the function does not seem to work properly. ...

Supported video formats in various web browsers

Are there detailed records of video codec compatibility across various desktop and mobile web browsers? ...

Challenges with splitting asynchronous code in NPM modules

Earlier, I posted a query on Stack Overflow I have recently established a local package within the main app's package.json: "contact-page": "file:local_modules/contact-page" The package.jsonmain and scripts sections for the contact module are confi ...

Choose the DIV element based on its data attribute using JSON

When using each(), my goal is to: Hide all divs where the data-infos.grpid = $jQuery(this).data('infos').grpid Show the next div where data-infos.ordre = $jQuery(this).data('infos').next_ordre I am unsure how to apply a "where" ...

Utilizing Angular 2's offline capabilities for loading locally stored JSON files in a project folder

I've been attempting to load a local JSON file from my Angular 2 project folder using the HTTP GET method. Here is an example of the code snippet: private _productURL = 'api/products/products.json'; getProducts(): Observable<any> ...