How to get element text with click using jQuery.text property?

I currently have a list of divs that have unique text. I would like the website to display the text value inside the div that you just clicked in another div. The fact is that this list is very long, and I do not have specific identifiers for any values โ€‹โ€‹in the list. Is it possible to pull text from this list with $(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);
});
});
+4
source share
3 answers

text () is a function, you need to call 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);
    });
});

: Fiddle

+3

text. , text()

 var $buildingName = $(this).text();
0

... - , $(this).text();

0
source

All Articles