If no image is found within the container, include a default image

I am currently working on this project. My goal is to display a default image if there is no image in the post. The JQuery code I have implemented is:

$(function () {
     $(".post").each(function () {
         var posthead = $(this).find("h2.post-title").text(),
             postlink = $(this).find("h2.posttitle a").attr("href");
         
         if($(this).find("img:first")>=1){
             var imageSrc=$(this).find("img:first").attr('src');
         }
         else{
             var imageSrc="http://3.bp.blogspot.com/-P5H7BaGibPg/UjVD-0SIs9I/AAAAAAAADFk/l65svtw9IHg/s320/70-photography-2.jpg";
         }
         
         $(this).replaceWith("<div class='post'><img class='thumb' src='" + imageSrc + "'/><div class='posthead'><h2 class='hometitle'><a href='" + postlink + "'>" + posthead + "</a></h2></div></div>");
     });

 });

This code will assign the attribute src of the first image as the variable imageSrc only if there is an image present. If not, it will use a default image specified in the else condition.

Answer №1

To determine if an image exists, you can use the length property of the jQuery object

Switch

if($(this).find("img:first")>=1){

with

if($(this).find("img:first").length>=1){

Check out the updated codepen

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

Updating a specific ID using jQuery in a Grails application - How can this be achieved?

I am working with a view file that looks like this: <html> <head> <meta name="layout" content="main" /> <title><g:message code="User's profile" /></title> <g:javascript library="jquery"/ ...

Tips for effectively monitoring scope for data loading

I have successfully created a custom Angular directive that utilizes D3.js to create a visualization. In my HTML, I reference this directive as follows: <gm-link-analysis data="linkAnalysis.connections"></gm-link-analysis> The relevant part o ...

Executing PHP Code with an External JavaScript File in an HTML Document

I have a script called initialize_database.js that utilizes JQuery to trigger a PHP script for creating a database and some tables. I made sure the PHP script is working correctly by adding HTML to test it independently, and it performed as expected. Below ...

Determining the measurements of an svg path without relying on the bounding box

Is there a way to retrieve the dimensions of an svg path and showcase it within a div without relying on the bounding box method? I've noticed that the bounding box can be buggy in Webkit especially with bezier curves. Just so you know, I am currently ...

Refresh the component data according to the vuex state

In order to streamline my workflow, I am developing a single admin panel that will be used for managing multiple web shops. To ensure that I can keep track of which website I am currently working on, I have implemented a website object in my vuex state. Th ...

What is the solution to the error message "cannot find specified file or directory, lstat 'scss/'"?

I am currently following a tutorial on YouTube here where the instructor is demonstrating how to run an npm script "sass" file using the terminal. When I try executing the command npm run sass, it gives me an error message: Error: ENOENT: no such file o ...

Implementing a see-through layer using CSS

This part of my site features a background image. I am attempting to add a transparent overlay at the top of this section, as indicated by the red highlight. I want to achieve this effect using CSS without directly applying the overlay to the image. The re ...

Tips on how to define an ajax request for the PHP section that is being managed

I recently started using ajax calls to retrieve information from php files and I have 7 elements in my html that trigger these calls. I've created 7 separate php files to handle each ajax call, like so: html part: <a style="cursor:pointer;" id="o ...

Placing icons in a treeview for optimal positioning

I am attempting to align the - and + icons to the right side of the tree line, just before the text "Mammals" and "Elephant." Here is the link for a demonstration: ...

What is the best way to apply ngClass to style a JSON object based on its length?

Currently, I am working with a mat-table that displays data from a JSON object. My goal is to filter out all records with an ID of length 5 and then style them using ngClass in my HTML template. How can I achieve this? Below is the code I am working with: ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

What is the best way to use @foreach to make the text in the final row of a table bold?

Is there a way to apply bold styling to the text in the final row using @foreach in HTML? I am looking to emphasize the total sum of each column by displaying it in bold text. While I initially considered creating a new table below the current one solely ...

Can values be transferred from an ng-repeat to a JavaScript function?

I am facing an issue with this segment: <tr ng-repeat="data in filtered = (list | filter:search | orderBy : predicate :reverse) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit"> <td>{{data.name}}</td> ...

Utilize Bootstrap 4 to create a full screen desktop layout with columns that automatically adjust to

I am struggling to create a full-screen layout using Bootstrap 4, similar to the one shown in this image. I'm facing issues with the left and right columns not taking up the remaining space between the navigation and footer sections. Additionally, I n ...

"Deactivate the escaping feature in PHP when using heredoc syntax

My PHP code generates minified JS output using the heredoc. Take a look at this snippet: function prerefresh(){$("#len").empty();predata.forEach(item)} I've highlighted that the {$ is causing issues with variable escaping in my heredoc. Is there a ...

When bullet points are aligned in the middle of wrapped text instead of the top line

When using bullet points on my Joomla site for a long sentence that wraps to multiple lines, I noticed that the bullets align with the middle of the wrapped text rather than staying flush with the top line. For example, if the text wraps to 3 lines, the bu ...

Discovering intersections between Polylines on Google Maps - a comprehensive guide

I'm currently developing a project involving a unique twist on Google Maps, focusing exclusively on natural hiking paths. My routes are built using GPX files converted into Google Maps polylines. Is there an efficient way to identify the intersection ...

How can I create a semantic-ui dropdown with a dynamically generated header?

Here are the dropdown options: const options = [ { key: '1', text: 'Example 1', value: 'Example 1', type:'ABC' }, { key: '2', text: 'Example 2', value: 'Example 2', t ...

Creating a Custom Class for a Custom Button in TinyMCE 4 Using addButton()

Is there a way to add a custom class to a custom button using the addButton() function in TinyMCE? Here is an example: editor.addButton('keywords', { text: 'Insert Keywords', class: 'MyCoolBtn', ...

"An issue with PHP not receiving any data from AJAX POST request

I've been working on creating a login using AJAX. The issue I'm facing is that when the AJAX function posts data to the PHP file, the data is empty when trying to retrieve it in PHP. Here is my AJAX posting code: function validateUser() { var ...