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

Retrieving user input in React by utilizing the onChange event handler

I have been tasked with creating a Quiz App and I am currently working on building it. The app consists of several components such as "question", "question-list", and "add-question". Within the "add-question" component, there is a form that allows users ...

Refresh WebPage automatically after a Servlet successfully uploads and processes an image

I have a webpage that includes an image and a button. When the button is clicked, it uploads the image by submitting a form to a file upload servlet. However, after successfully uploading the image, the servlet does not display it in the img tag. Here is ...

Issues with SVG Image Mask in Firefox and IE: How to Fix Them

Creating a mask with a PNG (black circle, transparent background) and using -webkit-mask-image:url(images/mask.png) has been easy for browsers like Chrome. However, I've been encountering significant difficulties in getting the mask to display properl ...

Exploring a JSON object within an AJAX request loop

Controller method: def get @projects = Project.get(params[:username]) render json: @projects.to_json end The JSON object returned by this controller method is passed as an array to the Ajax call shown below Ajax call : endpoint = ROOT_PAT ...

Utilizing jQuery to conceal table rows, streamlining the process

Currently, I am attempting to dynamically show and hide table rows using a toggle link that reveals or conceals them when clicked. While I have successfully implemented this feature, I am exploring ways to create a more generic function instead of duplic ...

I am facing an issue where Bootstrap button classes are duplicating when I inspect the code. How can I resolve this

Can anyone help me with an issue I am facing with a Bootstrap button? Despite using only the btn btn-default classes, when inspecting it in Chrome, multiple classes are being displayed on the button. I'm unable to figure out why this is happening and ...

Having difficulty including my JavaScript file located in /app/assets/javascripts when using Rails 4 and "//= require_tree ." in application.js

I'm currently attempting to implement a d3.js graph into my Rails 4 application by following a tutorial found on this website. The example application provided on GitHub works perfectly as expected. The issue I am facing is that when I try to recreat ...

Implementation of multiple angular guards causing a crash on the page

I have been attempting to implement separate guards for distinct pages. Essentially, I am checking a boolean parameter to determine if a user is logged in or not. Below are the two guard.ts codes that I am using: export class IsAuthenticatedGuard implemen ...

Preloading not working in Bootstrap Ajax Tabs

I've encountered an issue with Bootstrap Tabs and Jquery in my Asp.net MVC5 web app. Tab 1 (30days) is not loading on page load despite my efforts to troubleshoot the code multiple times. Could someone please review and identify where I may be going w ...

The current situation is not effective; it is causing an error saying "Uncaught TypeError: Cannot read property 'substring' of undefined"

Encountering an error "Uncaught TypeError: Cannot read property 'substring' of undefined" while debugging in Chrome Inspector, with the following code: <script type="text/javascript"> $(function countComments() { var mcount = '/ ...

Struggling with TypeScript and JsObservable? Let us assist you!

Having previous experience with JSRender, JSViews, and JSObservables, I recently embarked on a new project using TypeScript. Unfortunately, I am struggling to understand how to properly utilize TypeScript in my project, especially when it comes to referenc ...

Webpage refreshing when resizing browser

Hey there, I'm facing an issue where my HTML website restarts whenever the browser size changes. Can someone please help me fix this? You can check out my website here I have uploaded my code files here: Code Files Link ...

Automatically save user input in form fields with the help of jQuery and AJAX technology

I'm working on a form that has various input fields, and I need the data entered by the user to be automatically stored in the database every minute. After the user submits the request, it will be processed in a struts file where database interactions ...

To begin utilizing Node.js modules, you must use the `#` symbol as the starting point

Quoting the Nodejs documentation, available at this link require(X) from module at path Y 1. If X is a core module, a. return the core module b. STOP 2. If X begins with '/' a. set Y to be the filesystem root 3. If X begins with './ ...

JQuery is blocking the submission of an HTML form

During my exploration of an AJAX/JQuery tutorial for a registration script that interacts with PHP/MySQL and is submitted via JQuery, I encountered a recurring issue. The problem lies in the form submitting directly to the action page instead of its intend ...

Ember application experiencing trouble displaying Facebook Like Box

Iā€™m currently facing an issue with integrating the like box into our ember app, specifically in a template named about. The problem arises when users enter the ember app from a different route, instead of directly accessing the about route. In such cases ...

Invoking a plugin method in jQuery within a callback function

Utilizing a boilerplate plugin design, my code structure resembles this: ;(function ( $, window, document, undefined ) { var pluginName = "test", defaults = {}; function test( element, options ) { this.init(); } test.pro ...

What is the best method for displaying the accurate calculated value based on an element?

Within my "ROI calculator," there is a feature that allows users to adjust different labels. One of these labels is called "onlineRevenue." The concept is to recommend the most suitable plan based on the user's online revenue. However, I have some re ...

What is the best way to display a Nested JSON structure without an object key?

Need help with extracting data from two different JSON structures. The first one is straightforward, but the second is nested in multiple arrays. How can I access the content? See below for the code snippets: // First JSON { "allSuSa": [ { ...

What is the alternative method in JavaScript for locating items instead of using indexOf?

I have a set of paths in an array. Some paths are classified as constants while others are labeled as dynamic. A constant path would be something like "/booking-success", whereas a dynamic path could be something like '/arrival/view/:job_or ...