Is it possible to retrieve the class of a related element without using jQuery?

To retrieve the value of 'I Love' from the class track-songs within the cousin element of 'p', I am looking to start from the point where 'show lyrics' (using arrow) is clicked, which is triggered by the 'a' element. While there are examples in jQuery for this task, I am specifically required to accomplish it using vanilla JavaScript for my homework.

Image

https://i.sstatic.net/GMGN5.png

Is there a way to achieve this without relying on jQuery?

Answer №1

When the show lyrics link <a> is clicked, you can access the text content of the corresponding track using the Element.closest() method with addEventListener() as shown below:

const text = this.closest('popular-item.column').querySelector('.track-songs').textContent;

Check out the demo:

document.querySelectorAll("a").forEach(function(el){
  el.addEventListener("click", function(){
    const text = this.closest('popular-item.column').querySelector('.track-songs').textContent;
    console.clear()
    console.log( text )
  });
});
<popular-item class="column">
  <div class="card-content">
    <p class="track-songs">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
  </div>
  <div class="card-footer">
    <a href="#">Show Lyrics</a>
  </div>
</popular-item>
<popular-item class="column">
  <div class="card-content">
    <p class="track-songs">Contrary to popular belief, Lorem Ipsum is not simply random text.</p>
  </div>
  <div class="card-footer">
    <a href="#">Show Lyrics</a>
  </div>
</popular-item>

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

Hiding or removing DOM elements with ng-bootstrap pagination

I am in the process of incorporating pagination into my project using ng-bootstrap pagination. In my HTML, I am combining an ngFor loop with the slice pipe to filter elements for display. <tr *ngFor="let bankAccount of bankingAccounts | slice: (p ...

Modifying the appearance and behavior of an element dynamically as the page is being loaded using AngularJS

Struggling with a challenge for two days now, I have attempted to implement a panel-box using bootstrap and AngularJS. Within the confines of a controller, my code looks like this: <div id="menu2a"> <div class="panel list-group"> <div ...

What is the best way to send information from child components to their parent in React

I'm facing a scenario where I need to increase the parent value based on actions taken in the children components. Parent Component: getInitialState :function(){ return {counter:0} }, render(){ <CallChild value={this.state.counter}/> ...

What is the best way to generate a "JSON diff" that can be displayed in the JavaScript console?

When working on my Angular project, I frequently encounter the need to compare JSONs in my Karma/Jasmine tests. It would be incredibly useful to have a console output showing what has been added and removed when comparing two structures. For example, ident ...

Could offering a Promise as a module's export be considered a legitimate approach for asynchronous initialization in a Node.js environment?

I am in the process of developing modules that will load data once and create an interface for accessing that data. I am interested in implementing asynchronous loading of the data, especially since my application already utilizes promises. Is it considere ...

Is there a way to modify AJAX response HTML and seamlessly proceed with replacement using jQuery?

I am working on an AJAX function that retrieves new HTML content and updates the form data in response.html. However, there is a specific attribute that needs to be modified before the replacement can occur. Despite my best efforts, I have been struggling ...

RXJS - Trigger a function based on a specific condition being fulfilled by a value emitted from an observable

I have created a search field with autocomplete functionality. By using an observable that monitors changes in the text field, I am able to trigger actions based on user input. this.term.valueChanges .debounceTime(300) .distinctUntilChange ...

Tips on modifying the message "Please fill out this field" in the JQuery validation plugin

Is there a way to customize the message "This field is required" in the Jquery form validation plugin to display as "このフィールドは必須です"? Changing the color of the message can be achieved using the code snippet below: <style type="tex ...

Unable to fetch data in CakePHP 3.x controller using jQuery AJAX POST

I've been searching everywhere and unfortunately, I can't seem to figure out why the data is not being sent to my controller when posting via ajax. Here's the jQuery code snippet: var newDate = {}; newDate['start' ...

Scrolling using JavaScript's 'smooth scrolling' feature is currently disabled

Background of the Issue: I am in the process of creating a one-page website using Twitter Bootstrap 3 within an ASP.NET MVC project. The Challenge: My current challenge involves implementing 'smooth scrolling' functionality that scrolls to the ...

Traversing through Object consisting of dual arrays within VueJS

Currently, I am working on a chat application built in VueJS and encountering an issue when attempting to display messages along with their respective timestamps. The challenge arises from the need to iterate through an object that contains two arrays: one ...

Are you familiar with using double conditional rendering in a React application?

Currently, I am in the process of creating a small clothing store application using React as a way to expand my skills. One feature I have implemented is a filter by price section. However, I am looking for a solution to handle cases where no items fall wi ...

When a Double Click event is activated in EaselJS, it also automatically triggers a Click event

Listening for Events function Solitaire() { this.table.addEventListener("click", this.handleClick.bind(this)); this.table.addEventListener("dblclick", this.handleDoubleClick.bind(this)); } Event Handling Solitaire.prototype.handleDoubleClick = f ...

Looking to set up an event listener for a customized checkbox in a Kendo UI Grid column with Vue Js?

Can someone help me figure out why my method checkboxToggle() is not working when I click on the checkbox? Here is the code snippet: ` Methods:{ toggleTemplate(){ let template = `<label class="switch" > <input type= ...

Firebase is not updating the number

Having just started with Firebase, I have been following all the guidelines for web Firebase auth. I have successfully managed to login, log out, and update all data except for the phone number. Despite receiving a success message in the console, my phone ...

Is there a way to dynamically create a Vue component for every tier of a nested JSON object without prior knowledge of the total number of tiers available?

I am working with JSON data that includes a list of retailers, some of which have subretailers that go multiple levels deep. My goal is to use Vue to generate markup that will show the parent retailer along with any nested subretailers underneath it, simi ...

Unable to retrieve a return value from an asynchronous waterfall function within a node module

A custom node module that utilizes async waterfall is working properly when run independently, but the AJAX callback does not receive the return value. //Node module var boilerplateFn = function(params){ async.waterfall([ function(callback){ ...

Node.js publication date displaying incorrectly

When I post a date to elasticsearch, I typically use Date.now() var unixtime = Date.now(); The output usually looks something like this: 1373508091156 To convert it, I then use the following code: var date = new Date(unixtime*1000); After conversion, ...

Is it possible to render an SVG using PDFTron?

Before, I attempted to utilize an Annotation.StampAnnotation to make a personalized annotation while using an SVG as the foundation image. Unfortunately, I discovered that the StampAnnotation does not allow the user to alter or set the color. Thus, I have ...

jquery method to make entire navigation bar clickable

I have a single menu bar. I recently discovered an interesting way to make the entire menu bar area clickable using jQuery. Design code snippet: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="MenuControl.ascx.cs" Inherits="MenuControl"%> ...