JavaScript appends a backslash character to a CSS class

I am attempting to populate index.html with the contents from an array using a JavaScript loop. However, I am encountering an issue where a CSS class for picture formatting is displaying some odd characters when rendered in the latest version of Firefox.

I would like to understand why this is happening, how to prevent it, or explore alternative methods to ensure that this CSS class is applied correctly in the final output.

function populateIndex(){
  $("#showRecipes").html("");
  let recipeList = "";
  for (i = 0; i < recipes.length; i++) {
    let recipeArticle = '<div>';
    articleRecipe += '<div class="recipePhoto">' //issue with the "\recipePhoto\" 
    recipeArticle += '<img src=/images/' + recipes[i].photo + '></div>';
    recipeArticle += '<div> <h1>' + recipes[i].title + '</h1></div>';
    recipeArticle += '<div class="card bg-light"><div class="card-body row"><div class="col-sm-6"><p>' + recipes[i].author + '</p></div><div class="col-sm-6"><p>' + recipes[i].time + 'minutes</p></div></div></div>'
    recipeArticle += '<div><p>' + recipes[i].method + '</p></div>'
    recipeArticle += '<div class="card-body row"><div><p>' + recipes[i].likes + '</p></div><div><button type="button" class="btn btn-sm"><i class="material-icons"aria-hidden="true">thumb_up</i></button><button type="button" class="btn btn-sm"><i class="material-icons"aria-hidden="true">thumb_down</i></button></div><div><p>' + recipes[i].dislikes + '</p></div></div>'    
    recipeArticle += '</div>';
    recipeList += recipeArticle;
  }
  $("#showRecipes").html($("#showRecipes").html() + recipeList);

This is the CSS class that I am attempting to use.

#recipePhoto {
    margin-left: auto;
    margin-right: auto;
    width: 100%;
    max-height: 500px;
    overflow: hidden;
    object-fit:cover;
}

Answer №1

The inclusion of backslashes in your code by Javascript is to escape special characters. To use double quotes within a string, you can either use single quotes like 'words " words ...' (as you have done) or double quotes like

"words  \" words ..."
as they essentially have the same effect.

It is recommended to use Template literals instead.

Consider trying this:

$("#mostrarRecetas").html("")
let listadoRecetas = "";
for (i = 0; i < recetas.length; i++) {
  
  let articuloReceta = `<div>
    <div id="recetaFoto">
      <img src="/images/${recetas[i].foto}" />
    </div>
    <div>
      <h1>${recetas[i].titulo}</h1>
    </div>
    <div class="card bg-light">
      <div class="card-body row">
        <div class="col-sm-6">
          <p>${recetas[i].autor}</p>
        </div>
        <div class="col-sm-6">
          <p>${recetas[i].tiempo} minutos</p>
        </div>
      </div>
    </div>
    <div>
      <p>${recetas[i].metodo}</p>
    </div>
    <div class="card-body row">
      <div>
        <p>${recetas[i].likes}</p>
      </div>
      <div>
          <button type="button" class="btn btn-sm" id="search-icon">
            <i class="material-icons" aria-hidden="true">thumb_up</i>
          </button>
          <button type="button" class="btn btn-sm" id="search-icon">
            <i class="material-icons" aria-hidden="true">thumb_down</i>
          </button>
      </div>
      <div>
        <p>${recetas[i].dislikes}</p>
      </div>
    </div>
  </div>`;

  listadoRecetas += articuloReceta;
}
$("#mostrarRecetas").html($("#mostrarRecetas").html() + listadoRecetas);

The mistake you made was in using

'<img src=/images/' + recetas[i].foto + '></div>'
. It should be corrected to
'<img src="/images/' + recetas[i].foto + '"></div>'

Answer №2

I attempted to trigger #recetaFoto by using the class name "recetaFoto".

The symbol "#" typically signifies an ID, but I decided to convert it into a class. However, I forgot to update it to .recetafoto in the CSS after making the switch in the script.

What a waste of time...

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

Steps to Safely Transmit the Password through Ajax() Function in jQuery

I have implemented a Password textbox that starts with an empty value. When the user clicks on it and enters a password, the password will be updated in the database upon leaving the textbox (onblur event). I have successfully achieved this using ajax(). H ...

Issue with fadeout() on absolutely positioned element loaded via AJAX in jQuery

Currently, I am utilizing AJAXify on a website project to implement page transitions and encountering some abnormal behavior with jQuery. Below is my code: HTML (I am transitioning through backgrounds using jQuery) <div id="backgrounds"> <img s ...

React child component does not refresh upon modification of an array property

In my main application, I have two subcomponents that both receive the same model property. The first subcomponent deals with a number prop from model.myNumberProperty, and the second subcomponent handles an array prop from model.myArrayProperty. When ch ...

Obtain the background color of an element using the source attribute in Selenium WebDriver

Understanding the x-path is crucial, such as < img id="" src="/A/A/B.png" style=""> My task involves identifying the color of the image, but unfortunately, the style attribute does not provide any information about color. It only includes details a ...

Tips for showcasing a dataset within a table using Angular.js ng-repeat

I am encountering an issue where I have to present an array of data within a table using Angular.js. Below is an explanation of my code. Table: <table class="table table-bordered table-striped table-hover" id="dataTable" > <tbody> ...

Incorporating RFID reader functionality into a website

I am currently facing an issue with integrating an RFID card reader into a web page. After some research, it seems that the solution involves creating an ActiveX component and using JavaScript. My question is, how can we go about building an ActiveX compo ...

Scraping JavaScript Content Webpages with VBA

I'm attempting to extract a table from the Drainage Services Department website. I've written the VBA code below, but it doesn't seem to be working. I suspect that the issue lies in the fact that this particular table is generated using Java ...

Leveraging retrieved API data to generate numerous components

Hey there! I'm new to JavaScript and I'm working on creating a todo list with fake ToDos from jsonplaceholder using Fetch. My goal is to fetch five different ToDos and display them in separate list items within my list. However, I'm encounte ...

Executing a jQuery event after a div's background-image has finished rendering

Greetings and thank you for sparing a moment. I'm curious to know if there exists a method through jQuery to execute a function immediately after a background image in a div has completed downloading and rendering. Imagine you have the following div ...

What sets apart a React component from a function-as-component in React?

React is really confusing to me right now. Take this simple react component for example: export default function Foo(){ return( <div> <div>some text</div> </div> ) } I want to add a child compone ...

When loading HTML using JavaScript, the CSS within the HTML is not properly processing. Leveraging Bootstrap 5 might help resolve

Currently utilizing bootstrap 5 for my project. I have a setup in index.html where I am loading the contents of nav.html using JavaScript. However, I am facing an issue wherein the CSS styling for the navbar is not being applied when loaded via JS. Strange ...

Oops! The Route.get() function in Node.js is throwing an error because it's expecting a callback function, but it received

Currently, I am learning how to create a web music admin panel where users can upload MP3 files. However, I have encountered the following errors: Error: Route.get() requires a callback function but received an [object Undefined] at Route. [as get] (C:&bso ...

Ways to resolve axios promise

My current task involves working on a GET request from an API. Upon receiving the response shown in the image, I noticed that the data presented in the promise is accurate. My goal is to display the letters and their corresponding promise data within the H ...

How to Align Two HTML Forms Using CSS

I've been experimenting with various methods, but I'm still unable to achieve the desired outcome. Currently, my setup looks like this: https://i.sstatic.net/fUXKr.png However, what I really want is something more like this: https://i.sstatic ...

I need to find a way to identify when empty JSON data is being submitted to my RESTful HTTP POST endpoint. This issue is causing

I've set up a REST endpoint to handle JSON data sent via an HTTP post request using XMLHttpRequest as my client. Everything seems to be working smoothly until I wanted to test how the server would handle receiving no data at all, specifically null. To ...

Determine the quantity of information transmitted to the client through the stream

My current setup involves an Express API that enables download functionality through stream piping from a fetch call to res. I aim to monitor the data downloaded for each account to keep track of data usage. Here is how I have implemented it: let bytesSent ...

What is the most efficient method to import multiple MaterialUI components using a shared namespace without requiring the entire library to be imported

In order to prevent name mixing with other libraries, I want my MaterialUI components to be under the same namespace. For example, ensuring that <Box> references <MaterialUI.Box> and not <SomeOtherLibrary.Box>. Although it seems like a si ...

Unable to deploy the Firebase function to Firebase functions platform

I've been watching Doug's video on YouTube for guidance on changing a message with functions in JavaScript. To resolve the error message 'types can only be applied to ts files,' I installed the Flow language script. Thankfully, that err ...

How to center items within a Toolbar using React's material-ui

I need help with implementing a toolbar on a page that contains three ToolbarGroup components: <Toolbar> <ToolbarGroup firstChild={true} float="left"> {prevButton} </ToolbarGro ...

Attempting to include html5shiv.js in my project to ensure compatibility with Internet Explorer for proper rendering

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="Description" content="C.V"/> The code snippet below was added to try and render in Internet Explorer, unfortunately it did not work as expected. < ...