Retrieve Text from a Different <div> Based on Class Using JQuery

Struggling with JQuery, I am trying to access text from another div using only classes. While not fully familiar with JQuery, I manage to make it work most of the time.

I attempted something like this:

$(function() {
$(".quote_button").click(
    function () {
        var text = $(this).parent('.openticket_footer').prev('.openticket_warper').find('.answer_message').text();
        alert(text);
    }
);});

Despite trying many other ways, I can't seem to figure it out.

A picture illustrates what I am aiming for:

Quote function

My goal is to click on the class="quote_button" button to access the text in class="answer_message". Here is the HTML code:

<div class="openticket_warper">
    <div class="openticket_sidebar float_left">';
        if($result["uID"]==$result_answer["uID"]){
           echo '<p style="font-size: 8pt">Ersteller</p>';
        }
        echo '<p><strong>'. $result_answer["uName"] .' '. $result_answer["Firstname"] .'</strong></p>
        <p style="font-size: 10pt">'. $result_answer["pName"] .'</p>
        <div class="openticket_sidebar_userpicture">
            <img src="images/default-user-icon.png" alt="User Picture">
        </div>
        </div>
        <div class="openticket_ticketmesssage">
            <p class="answer_message">'. $result_answer["Message"] .'</p>
        </div>
        <div class="clear"></div>
    </div>
    <div class="openticket_footer">
        <input class="answerbutton float_right quote_button" type="button" value="Zitieren">
         <div class="clear"></div>
    </div>

Thank You!

Answer №1

Here's a suggestion: Use the parent method to find the parent element, then navigate to the previous div and locate the answer_message to retrieve the text

$(function() {
  $(".quote_button").click(function () {
    var $parent = $(this).parent('.openticket_footer').prev('.openticket_warper');
    var text = $parent.find('.answer_message').text();
    alert(text);   
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="openticket_warper">
    <div class="openticket_sidebar float_left">';
        <p style="font-size: 10pt">Name of the candidate</p>
        <div class="openticket_sidebar_userpicture">
            <img src="images/default-user-icon.png" alt="User Picture">
        </div>
        </div>
        <div class="openticket_ticketmesssage">
            <p class="answer_message">Text Message is here</p>
        </div>
        <div class="clear"></div>
    </div>
    <div class="openticket_footer">
        <input class="answerbutton float_right quote_button" type="button" value="Zitieren">
         <div class="clear"></div>
    </div>

Answer №2

$(document).click(function(){ let quote = $(this).closest('.openticket_wrapper').find('.response_text').text(); if(quote){ alert(quote); } else { console.log('No response text found'); } });

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

Using JQuery to animate a div tag and automatically hide it after a specific duration

I'm attempting to create an animation where a div tag moves left 300px, hides after 3 seconds, and then repeats the process every 8 seconds. However, my current code only runs the animation once and doesn't repeat the entire process. Below is the ...

Discovering a device's model using JavaScript

How can I use Javascript to redirect users to different download pages based on their device model? ...

Trouble retrieving desired data from an array of objects in React Native

I'm having trouble retrieving values from an array of objects in my state. When I try to access the values, it only prints out "[Object Object]". However, when I stored the values in a separate array and used console.log, I was able to see them. Here ...

Verify the presence of the input post in the mongo database

Currently, I am utilizing the following node js code to store data in a database... //connect to database db.on('error', console.error); db.once('open', function() { router.post('/register', function(request, response) { ...

JavaScript Ping Pong Challenge

I'm currently investigating why the browser returns NaN for the Positions. The game is being rendered in a loop and updated as soon as the monitor is ready, which is defined in the update() function and runs infinitely. The reset() function is a part ...

Enhance and streamline custom module code within a Node.js Express application

I am seeking suggestions on how to optimize the code within my custom module. Below is the code for my module which you can review and provide feedback on. var employee = { all: function (req, res) { jwt.verify(req.token, 'novatureso ...

Leveraging Knockout observables that are fueled by JSON data to dynamically refresh the view

Exploring Knockout observables in relation to my previous inquiry on Stack Overflow. Check out the question here. I'm aiming to dynamically update the view with either 'red flower' or 'blue sky' based on the button clicked, assumi ...

Tips for exchanging JSON data between HTML and PHP using jQuery Ajax?

Hello there! I am just starting to learn PHP and jQuery, and I have been experimenting with some code to understand how things work. However, I seem to be having issues with sending data back and forth between my webpage and the PHP file on the server. Her ...

Creating visual content on Canvas using JavaScript

Having an issue with stacking multiple images on separate Canvas layers, and they're not drawing on the canvas. Can anyone help me figure out what I'm missing? Thanks CSS .positionCanvas{ position: absolute; left:0; righ ...

Utilizing XMLHttpRequest in JavaScript to interact with Elasticsearch

Having trouble making a GET request to another website from work, but when attempting to request from Elasticsearch using localhost it is not working. The status codes returned are: Create Object from JSON String 4, 0, readyState = 4 status = 0 Below i ...

How to keep a div element fixed on the page's border vertically and horizontally adhered

Would you mind visiting the following link: and observing the layout of the page? My goal is to affix or "attach" a small div element to the right side of the page, just slightly outside of the right frame of the page. Vertically, I want this div to be ...

Sending a PHP variable to jQuery using AJAX

I am working on a project where my ajax function in jquery is calling a php file to interact with the database. However, the result of this operation can vary. Depending on whether it succeeded or not, I want to output a different message. Currently, I ha ...

Retrieve information from an HTML input field that does not have an assigned ID or name

I am facing a challenge with an HTML table that contains multiple inputs which do not have any id or name attributes. I need to retrieve data from these inputs but struggling due to the lack of identifiers. Upon inspecting the DOM, I noticed that each inp ...

Utilize the value of a variable as the name of a different variable within

In the following code snippet: DbModels.prototype.updateById = function(_collection, id, field, value, callback) { this.getCollection(_collection, function(error, sel_collection) { if( error ) callback(error) else { sel_collection. ...

Tips for decreasing the file size without compromising the clarity of the image?

Currently, I am working on an image puzzle project using jQuery. Everything is almost complete, except for one issue: when the user selects the 2x2 puzzle, the cropped image size appears too large (the original cropped size). I need to reduce the size of t ...

Tips for displaying identical tab content across various tabs using jquery or javascript

For instance, if we have tabs labeled as 1, 2, 3, 4, and 5, and a user has selected tabs 2, 3, and 4, how can we display the same content for those tabs while showing different content for the remaining ones? ...

Customizing font sizes for individual fonts within the same font family

I am designing a website in a language other than English. This means that the text on the webpage will be a mixture of English and other languages. In order to make sure the text displays correctly, I have set the font-family like this: p{ font-family: ...

How can I replace the unsightly "Web page not available" error in WebView on Android with a more visually pleasing alternative?

In my WebView Activity, I sometimes encounter issues with loading properly when the WIFI/DATA connection is poor or disconnected. This could potentially be a common occurrence once my app is in use. I'm curious to know how I can replace the unattracti ...

What is the way to instruct Mongoose to exclude a field from being saved?

Is there a way in Mongoose to instruct it to not save the age field if it's null or undefined? Or is there a method to achieve this in Express? Express router.put('/edit/:id', function(req, res) { Person.findOneAndUpdate({ _id: req.p ...

Utilizing Jison/Bison for string analysis

I'm currently diving into the world of Jison, a Javascript parser generator utilizing Bison syntax. My current code snippet resembles the following: a: "{{index()}}" b: "{{blah(2, 'aba')}}" My goal is to develop a parser that can interpre ...