Choose the initial p tag that includes an image, based on the content of another div

I am trying to figure out how to manipulate the code on my website:

<div class="the-post-thumbnail">
    <img src="" alt="" width="" height="" />
</div>

<div class="post-body">
    <p><img src="" alt="" width="" height="" /></p>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p><img src="" alt="" width="" height="" /></p>
</div>

Does anyone know how to target the first <p> tag containing an image within the post-body div and either hide it if there is an image in the the-post-thumbnail div, or show it if not?

CODEPEN

Answer №1

If you want to manipulate the visibility of certain elements using jQuery, you can make use of the :has() and :first selectors.

  1. With the :has() selector, you can target the p tag that contains an img tag.
  2. Using :first, you can specifically target the first p tag that meets the criteria.
  3. For toggling visibility, you can utilize hide() and show() methods.

EXAMPLE CODE:

var targetElement = $('.post-body p:has(img):first');
if ($('.the-post-thumbnail img').length > 0)
  targetElement.hide();
else
  targetElement.show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="the-post-thumbnail">
  <img src="" alt="#" width="" height="" />
</div>

<div class="post-body">
  <p>
    <img src="" alt="#" width="" height="" />
  </p>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>
    <img src="" alt="" width="" height="" />
  </p>
</div>

Answer №2

// Set $el as the first paragraph containing an image within div.post-body
$el = $("div.post-body").find("img").eq(0).closest("p");

// Check if there are no images in the post thumbnail and hide or show $el accordingly
if($(".the-post-thumbnail img").length==0)
  $el.hide(); 
else
  $el.show()

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

Tips for adding and verifying arrays within forms using Angular2

Within my JavaScript model, this.profile, there exists a property named emails. This property is an array composed of objects with the properties {email, isDefault, status}. Following this, I proceed to define it as shown below: this.profileForm = this ...

What are the benefits of using Array.prototype.forEach.call(array, cb) instead of array.forEach(cb)?

After revisiting some snapshots from the recent ng-europe conference, I stumbled upon a slide that appears to showcase snippets of code from Angular 2. You can view it here: (Source: ) One thing that confuses me is this: What could be the reason behind t ...

Maintain the same javascript variable throughout multiple pages

I am working on a project that involves utilizing a database along with 2 drop down menus. Through the use of JavaScript, I am able to capture the value selected from the drop down menus and then pass it on to my PHP script. The PHP script retrieves releva ...

Leveraging the power of AJAX for sending post requests in a Node.js Express application with

I have a newsletter section on my website that collects name and email information. I want users to be able to submit the form without reloading or redirecting the page, saving their data in MongoDB for future use in sending newsletters. It would also be c ...

Tips for sending an ID to a path link in React Js

Can anyone assist me in setting up a path for a component like this "/products?id=uniqueId" in my React Js Project? The unique id is retrieved from the database and varies depending on the product chosen. Below is an excerpt of my code: CodeSandbox App.j ...

A Guide to Implementing Inner CSS in Angular

I am working with an object named "Content" that has two properties: Content:{ html:string; css:string } My task is to render a div based on this object. I can easily render the html using the following code: <div [innnerHtml]="Content.html"& ...

Tips for choosing a drop-down menu option without an identifier using Selenium in Python

I am trying to choose an element/item from a drop-down menu in Python and Selenium without using an id element. Here is the HTML code snippet: <mbo-transaction-mode-select mode="filters.mode" class="ng-isolate-scope"> <select class="form-con ...

Firefox having trouble displaying styles correctly

I just finished creating a website for my band, but I am having issues with it displaying correctly in Firefox. While everything looks great in Chrome and Safari, it seems like the stylesheet isn't loading at all in Firefox, leaving the page looking u ...

Insert a new <tr> element into a dynamic table using PHP and jQuery without the need to refresh the page

I am attempting to dynamically insert a row into an existing table when a button is clicked. The rows in the table are created dynamically based on data retrieved from a PHP script. My approach involves making an ajax call to the insert_tr.php script, whi ...

Tips for securely transmitting data via a hidden form using the POST method

I have a query that displays records of people, and I want to send the id_Persona using a hidden form through a post function to the idsPersonas.php page. However, when I try to do this, it redirects me to an undefined page. Here is the code snippet: < ...

Which method is more effective: embedding PHP processing code within HTML files, or having forms redirect to separate PHP scripts that ultimately point back to static pages?

I'm in the process of developing a new website, and I'm still learning about PHP. Would it be more advantageous to use .html pages where buttons with Onclick would trigger JavaScript functions that redirect to a PHP page for database interaction ...

Unable to create slides with Fancybox if the content is in HTML format

I'm not sure if this issue is a bug or if it's just a restriction of fancybox. Can anyone confirm if it's possible to create a gallery using HTML elements? I've been attempting to accomplish this for hours without success. Here is the ...

Tips for retrieving data from a JSON array

I have a JSON object that looks like this: var obj={ "address":{ "addlin1":"", "addlin2":"" }, "name":"sam", "score":[{"maths":"ten", "science":"two", "pass":false }] } Now, when I attempt to m ...

Using CSS properties as false values within React applications

Can you provide guidance on using conditional styles with conditional operators? What would be the ideal code example? Is it possible to use non-CSS values? margin: isOpen ? '10px' : undefined margin: isOpen ? '10px' : 'initial&a ...

Improve the way you manage return statements

Here is the function in question: const checkifHaveBomb = (column, row) => { let isBomb = false activeBombContainer.forEach(element => { if (element.column === column && element.row === row) { ...

Tips for creating a stylish navbar with a faded effect on the right side and integrating a fresh button into its design

I'm looking to enhance my Navbar by implementing a feature where, if the width of the Navbar exceeds that of its parent div, it will fade on the right side and a new button will be added - similar to what can be seen on Youtube. 1- When the Navbar&ap ...

Warning message will appear before navigating away from the page if vee-validate is

Wondering how to create a simple confirmation prompt asking if the user really wants to leave a page that includes a basic HTML form. The HTML Form: <!DOCTYPE html> <html> <head></head> <body> <div id="app"> ...

The CSS styling feature is not functional within the JavaMail API

After receiving an email sent using the JavaMail API, I noticed that the CSS styles are not being applied and only the HTML content is rendered. HTML CODE <!doctype html> <html lang="en"> <head> <meta charset="u ...

Fulfill the promise within the $stateProvider and proceed with utilizing the outcomes

I am facing an issue where I need to resolve a promise in a state provider so that I can use the results of the promise in another promise. I am a bit unsure about how to go about this. I tried the following approach: app .config(['$stateProvid ...

Is there an alternative, more efficient method to invoke this JavaScript code received through an AJAX request?

I am curious about the use of the eval() function in my code. While it works, I have read that it is not considered best practice to use eval(). I have a scenario where I receive a response from an AJAX call, which is essentially a webpage containing some ...