How can I retrieve the text of a clicked element using jQuery's .text property?
html, jquery, text, this
Solution
text() is a function, you need to invoke it to get the text of the clicked element
var $buildingName = $(this).text();// <-- () at the end
$('span').text($buildingName);
Your code can be rewritten as
jQuery(function ($) {
//these selectors are executed only once
var $span = $('#jstext');
$('.buildings').hover(function () {
$(this).css('background-color', '#D8BFD8');
}, function () {
$(this).css('background-color', '#F0EAD6');
}).click(function () {
var buildingName = $(this).text();
$span.text(buildingName);
});
});
Demo: Fiddle
Problem
I currently have a list of divs that all have unique text. I would like the website to display the value of the text inside the div that you just clicked in a different div. The thing is, this list is very long, and I do not have specific IDs for any values in the list. Is it possible to pull text from that list using `$(this).text`? I could not get it to work. HTML: ``` <!DOCTYPE html> <html> <head> <title>Facilities Management</title> <link rel='stylesheet' type='text/css' href='stylesheet.css'/> <script type='text/javascript' src='script.js'></script> </head> <body> <div class='wrap'> <div class='banner'>Facilities Management</div> <div class='menu1'> <div class='menu2'> Where do you live? <br><br> <div class='buildings'>building 1</div> <div class='buildings'>building 2</div> <!--- and so and so ---> </div> </div> <div class='main'> <span id='jstext'></span> </div> </div> </body> </html> ``` JQuery: ``` $(document).ready(function() { $('.buildings').mouseenter(function() { $(this).css('background-color','#D8BFD8'); }); $('.buildings').mouseleave(function() { $(this).css('background-color','#F0EAD6'); }); $('.buildings').click(function() { var $buildingName = $(this).text; $('span').text($buildingName); }); }); ```