Acquire the content of a nested element using jQuery

I have a navigation list with separate headlines and text for each item. The goal is to switch the main headline and paragraph of text when hovering over a navigation item.

CodePen Example

Currently, my code displays all text. I only want to display the H1 & P text within the class name .spot_titles: https://codepen.io/example123/

To better illustrate what I'm aiming for:

When hovering over an item like Acne or Oiliness, the headline and text should change accordingly. This represents the active state and my desired outcome:

JavaScript

// Retrieving the original content
var main_url = $(".index__hero-image").css('background-image');
var main_title = $(".index__hero-image h1").text();
var main_text = $(".index__hero-image p").text();

$(".index__spot").hover(function () {
  var image_url = $(this).css('background-image');
 
  // Adjusting the variables here may be needed.
  var spottitle = $(this).text();
  var spottext = $(this).text();

  $(".index__hero-image").css('background-image', image_url);
  $(".index__hero-image h1").text(spottitle);
  $(".index__hero-image p").text(spottext);
},
function() {
  // Reverting to original content when not hovered
  $(".index__hero-image").css('background-image', main_url);
  $(".index__hero-image h1").text(main_title);
  $(".index__hero-image p").text(main_text);
});

HTML

<div class=" index__text-block">
  <h1>Original headline</h1>
  <p>Original text block goes here</p>
</div>

<div class="solutions-bar">
<a href="acne.html" class="index__spot" style="background-image: url('http://placeexample.com/700/700');">
<!-- Ignore next 3 lines / Create the icon in the link list -->
<img src="icon.png">
<h6 class="content-1">Acne</h6>
<h6 class="content-2">Shop Now</h6>

<!-- Use this text to replace that in index__text-block -->
<div class="spot_titles">
  <h1>Acne headline</h1>
  <p>
    Some text related to acne
  </p>
</div>

Answer №1

Revise these lines:

var spottitle = $(this).text();
var spottext = $(this).text();

to the following:

var spottitle = $(this).find('.spot_titles h1').text();
var spottext = $(this).find('.spot_titles p').text();

This code will retrieve the content of h1 inside the .spot_titles element and the content of p within .spot_titles.

You can learn more about the find() method by visiting the jQuery API Documentation.

Answer №2

When targeting the child element text, it is recommended to utilize .find() with a valid selector.

// It appears that these variables below are incorrect.
var spottitle = $(this).find('.spot_titles h1').text();
var spottext = $(this).find('.spot_titles p').text();

Fiddle

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

what is the best way to center list items in material ui?

I have been attempting to align the list items (checkbox, text, and buttons) within a Material UI list in the center, but all my attempts have been unsuccessful. Is there anyone who knows how to resolve this issue? Your help would be greatly appreciated! h ...

Switch the CSS class for the currently selected link

There are 5 links on the page. When I click on each link, it changes color. However, when I move my cursor to another area of the page, the active link loses focus and I can't show its current state. Can you please advise me on how to fix this issue? ...

JQuery Falters in Responding to Button's Click Action

Forgive me for what may seem like a silly question, but as someone new to JQuery, I have been struggling to figure out why my function is not displaying an alert when the button is clicked. Despite thorough research on Google, I haven't been able to f ...

What is the best way to execute multiple Protractor test suites simultaneously?

Exploring Protractor for the first time. My goal is to run multiple test suites in a sequence. I have a complex angular form with various scenarios, each with its expected results. I want to execute all tests with just one command. Initially, I tried enter ...

Running the command npm show --outdated triggers an E404 error stating that the package is not found in this registry

I am currently working on a confidential project that I prefer not to make public. Despite using node v17.3.0 and npm 8.3.0, I am facing difficulties in displaying the outdated dependencies: $ npm show --outdated npm ERR! code E404 npm ERR! 404 Not Found - ...

What is the best way to incorporate an AJAX GET request into an HTML element?

Currently, I am attempting to execute a JavaScript code that will convert all <a></a> elements found within another element <b></b> (the specific name in the HTML) into links that trigger an HTTP get request. However, the code I hav ...

Sequelize.Model not being recognized for imported model

I am encountering an issue while trying to implement a sequelize N:M relation through another table. The error message I keep receiving is as follows: throw new Error(${this.name}.belongsToMany called with something that's not a subclass of Sequelize ...

Using JQuery to overlay the entire page within the content placeholder

Currently, I am facing an issue with blocking the entire page using jQuery. Despite my best efforts, the block only affects the 3rd content placeholder area instead of the whole page as intended. My code snippet using jQuery is as follows: <script lan ...

Error: The function Undefined is not recognized by express.io

Struggling to configure express.io with individual files for each route? Check out the examples provided. Currently, I have a typical Express setup that I want to transition to express.io: Project app.js routes servepage.js Views ...

Show me a way to use jQuery to show the number of images of a particular type that are on a

My webpage features 6 different images, including 4 of various balls such as basketball and baseball. One image is of a truck, while the last one is random. On the page, there is a form with two radio buttons allowing users to select which type of image c ...

JavaScript variable is showing as a string but is printing as: "[object Object]"

Currently, I am working on parsing wikipedia documents using the npm package html-to-text to extract text from various wikipedia pages. However, I have been facing issues when trying to log or send this content for use on the client side. Below is how I a ...

Identify when the user intends to open the link in a new window or tab

I am developing an AJAX application where all links on the page are JavaScript links (href="javascript:void(blahblah)"). Some of these links open small webpages in an iframe within a positioned div element that can be moved around. While this design looks ...

How to locate the cell with a specific class using JavaScript/jQuery

I need help with the following code snippet: var output = '<tr>'+ '<td class="class1">One</td>'+ '<td class="selected">Two</td>'+ '<td>< ...

Expanding a collection of text inputs on-the-fly (HTML/JavaScript)

Looking to streamline our data entry process, I am developing an app for in-house tasks. Our team will be required to input information about various "items" that correspond to multiple "categories." To facilitate this task efficiently, I'm explorin ...

Incorporating script within an ASPX webpage

I've been struggling with using this code on an ASPX page. I keep trying to implement it within a text box on the same page, but without success. Strangely though, I can successfully use the script within a text box in my master page. Any assistance w ...

What is the best choice for the navigation menu: using `<ul>` or `<div>`?

Is it considered unprofessional to construct a navigation menu without utilizing unordered list tags? For instance, opting for <div> elements instead. <div class="navbar"> <a href="#"> Home </a> </div> ...

Unexpected behavior encountered when using the $http.post method

I've been working with a component that I utilized to submit data to the Rest API. The code snippet for the component is as follows: (function(angular) { 'use strict'; angular.module('ComponentRelease', ['ServiceR ...

What is the most effective method for determining if an object contains a particular property?

Can anyone advise on the best approach to check if an ajax response object has a specific property? I've done some research and it seems there are various methods to do this. One way is: if(ajaxResponse.hasOwnProperty('someProperty')){ ...

When retrieving data from a PHP $_SESSION using an Ajax $_POST call, outdated information is being returned

I am encountering an issue that I cannot seem to figure out. Currently, my application consists of three pages: Home.php Nearmiss.php Reports.php Each of these pages includes code at the top with a specific "thispage" variable unique to that page. < ...

Enhance your Kendo UI File Manager by incorporating image uploading and folder renaming capabilities

Currently utilizing the kendo UI file manager to navigate through my files and images. According to telerik documentation, only the functions to add folders and remove files and folders are supported. However, I am in need of the ability to rename both f ...