Provide alternative styling through css in instances where the Google Books API does not provide an image

How can I modify the CSS code to display the author and title of a book when there is no image available from the Google Books API?

Currently, users see a custom image linked here, but it's not clear what it represents without the name and author information.

const extractThumbnail = ({ imageLinks }) => {
const DEFAULT_THUMBNAIL = "https://www.bindly.pl/static/images/logo.svg";
if (!imageLinks || !imageLinks.thumbnail) {
    return DEFAULT_THUMBNAIL;
}
return imageLinks.thumbnail.replace("http://", "https://");};

Instead of return DEFAULT_THUMBNAIL;, I want to remove the image and apply the following CSS:

document.querySelector("div.book-info ").style.display = "inline-flex;";
document.querySelector("h3.book-title").style.fontsize = "32px";

However, these changes don't seem to be working...

Any suggestions? Here's the entire code snippet:

let bookContainer = document.querySelector(".search");
let searchBooks = document.getElementById("search-box");
const getBooks = async(book) => {
    const response = await fetch(
        `https://www.googleapis.com/books/v1/volumes?q=${book}&langRestrict=pl&printType=books`
    );
    const data = await response.json();
    return data;
};

const extractThumbnail = ({ imageLinks }) => {
    const DEFAULT_THUMBNAIL = "https://www.bindly.pl/static/images/logo.svg";
    if (!imageLinks || !imageLinks.thumbnail) {
        return DEFAULT_THUMBNAIL;
    }
    return imageLinks.thumbnail.replace("http://", "https://");
};

const drawChartBook = async(subject, startIndex = 0) => {
    let cbookContainer = document.querySelector(`.${subject}`);
    cbookContainer.innerHTML = `<div class='prompt'><div class="loader"></div></div>`;
    const cdata = await getBooks(
        `subject:${subject}&startIndex=${startIndex}&maxResults=3`
    );
    if (cdata.error) {
        cbookContainer.innerHTML = `<div class='prompt'></div>`;
    } else if (cdata.totalItems == 0) {
        cbookContainer.innerHTML = `<div class='prompt'></div>`;
    } else if (cdata.totalItems == undefined) {
        cbookContainer.innerHTML = `<div class='prompt'>ツ Ups, chyba masz problem z internetem!</div>`;
    } else if (!cdata.items || cdata.items.length == 0) {
        cbookContainer.innerHTML = `<div class='prompt'>ツ Niestety, nie ma więcej wyników!</div>`;
    } else {
        cbookContainer.innerHTML = cdata.items;
        cbookContainer.innerHTML = cdata.items
            .map(
                ({ volumeInfo }) =>
                `<div class='book' style='background: linear-gradient(` +
                getRandomColor() +
                `, rgba(0, 0, 0, 0));'><a href='https://www.bindly.pl/${volumeInfo.authors}/${volumeInfo.title}' target='_blank'><img class='thumbnail' src='` +
                extractThumbnail(volumeInfo) +
                `' alt='cover'></a><div class='book-info'><h3 class='book-title'><a href='https://www.bindly.pl/${volumeInfo.authors}/${volumeInfo.title}' target='_blank'>${volumeInfo.title}</a></h3><div class='book-authors' onclick='updateFilter(this,"author");'>${volumeInfo.authors}</div></div></div>`
            )
            .join("");
        document.querySelector(".search-box").style.background = "#f00;";

    }
};

Answer №1

The issue arises when you attempt to set the style properties using:

document.querySelector("div.book-info").style.display = "inline-flex;";
document.querySelector("h3.book-title").style.fontsize = "32px";

[By the way, there are syntax errors present here - such as the ; before the " in the first line and fontSize should be written in camel case. Nevertheless, these mistakes aren't causing your problem assuming that this code is being called within the extractThumbnail function.]

The elements you are trying to access have not been added to the DOM yet - they haven't even been included in the string that you are constructing to eventually place into the document.

One potential solution is to create strings within the extractThumbnail function which can later be appended to the HTML being constructed. For instance, you could have a string representing the entire thumbnail img element - and if there's no thumbnail, make that string null. Create additional strings for styles like 'display: inline-flex;' and font-size. Then insert them into the HTML string gradually while calling the extractThumbnail function beforehand.

If the extractThumbnail function is utilized elsewhere, consider creating a separate version specific to this scenario with a distinct name to prevent interference with other parts of the code.

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

Exploring the basics of utilizing React Testing Library to test a component - a beginner's dive into this innovative testing tool

I've been working on learning how to test 2 components using react-testing-library, but I've hit a roadblock. The component in question is NestedLists.js import React from 'react' export const NestedLists = ({filteredData}) => { ...

Opting for <button> over <a>

I am currently working with ReactJS in conjunction with a Bootstrap Nav Bar. Bootstrap utilizes an <a> tag for the navigation buttons. I am aiming to have the buttons scroll down to a different component on the page without resorting to using an href ...

How can I write a JavaScript function that eliminates all white spaces within a string?

Exploring ways to create a custom function that trims white spaces from the beginning and end of a string (including \n, \t) without relying on built-in methods like trim(), replace(), split(), or join() Here’s an example code snippet showcasi ...

Exploring the functionality differences between mouse wheel tilt and scroll in JavaScript with scrollTop

Did you know that some computer mice come equipped with a scroll wheel that can tilt both left and right? This feature allows users to navigate through Google's piano roll app, which can be accessed here (source code available here). I am working to ...

loop through the links using their unique identifiers

Here is my current code in Jade/Pug: #pm_language.dropdown(aria-haspopup='true', aria-expanded='false') button#langbutton.btn.btn-primary.dropdown-toggle(type='button', data-toggle='dropdown') Lang [RU] ...

Javascript window.scroll function malfunctioning in some browsers while running in localhost

Check out this codepen link where everything is working, but unfortunately not locally: https://codepen.io/LoudDesignStudios/pen/RwxPJKY <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> < ...

The alert box is not displaying, only the text within the tags is visible

Trying to implement an alert message for logged-in users. A successful login will trigger a success message, while incorrect username or password will display an error. function showMessage(response) { if (response.statusLogged == "Success login") { ...

How can I use HTML to replace specific text or blocks within the DraftJS Editor?

Incorporating Rich Text capabilities into my React-based web application using DraftJS Editor has been a focus of mine. One specific requirement I have is the ability for a user to trigger a drop-down menu by typing the "#" key next to the editor. From th ...

How can React and Redux ensure that response data is accessible to every component?

When using react and redux, how can data written in the useDispatch function be made available in other components? Additionally, how can the customerId be accessed in all components? I have created a code that calls an API and returns data in response. I ...

Is there a way to input data into an AngularJS modal?

I'm looking for some assistance : How do I go about loading data into the content of an angular modal? Is there a way to load custom data for a selected item? ............................................................. This is the code ...

What to do when IE6/IE7 margins disappear after moving a relatively positioned floated div using jQuery's .hover()?

Sharing my code with you: http://jsbin.com/uhera3/edit Encountered an issue where the relatively positioned floated divs move to the left in IE7 when using jQuery's .hover() function. Any insights on how to resolve this problem? ...

Master the art of filtering rows in an HTML table based on a select option when the mouse is clicked

I am trying to create a table that displays only the rows selected in a dropdown menu. Here is an example: If "All" is selected, the table should display all rows. If "2017" is selected, the table should display only the rows that have "2017" in the sec ...

Halt the iteration once you reach the initial item in the array

I am encountering a challenge with this for loop. My goal is to extract the most recent order of "customers" and save it in my database. However, running this loop fetches both the failed order and the recent order. for (var i = 0; i < json.length; ...

The default action is not triggered when the click event occurs

Hey there, I have been working on this <ol> list of events using jQuery (version 1.4.2). Everything is set up within the $(document).ready() function. Something strange is happening where when I click on the <li>, it triggers a click on the co ...

Concealing spinner controls on HTML Ionic number input

Seeking a foolproof method to conceal spinner buttons on an HTML template for Ionic's number input field. Showcased below is the HTML code that exhibits an input with spinner buttons: <ion-input type='number'></ion-input> The ...

Personalized path-finding tree iterator

I am trying to implement a custom iterator in JavaScript that can traverse a DOM tree based on specific criteria provided by a callback function. The goal is to return an array of the nodes that match the criteria as the generator iterates through the tree ...

Issue with JavaScript-generated dropdown menu malfunctioning in WebView on Android devices

During my testing of the app on a Galaxy Tab with Android 2.2, I encountered an issue within the WebView component. The problem arises when I have a local HTML page generated dynamically and it contains a SELECT element like this: <select class='d ...

Having trouble with flash messages in Node.js?

Could anyone shed some light on why the flash messages are not displaying properly in my situation? Here is how I'm attempting to utilize them: This snippet is from my app.js file: var express = require('express'); var app = express ...

Displaying from the left side to the right side

Having some issues with sliding from the left to right div that has display:none. <div class="second"> <li><a id="sale_man" rel="showinfo"><?php echo $lang['sale_man'];?></a></li> <li><a id="purch_man ...

Switch Image to Background Image on Mobile Devices

I am currently working on a website that needs a special page for an upcoming event. Typically, the pages on this site have a mast banner image that stretches across the full width of the page. However, for this particular page, it is necessary for the ima ...