Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract data from collection made by jQuery selector?

Just a small example. I have 3 links, a button and a div:

<a href="#">AAA</a>
<a href="#">BBB</a>
<a href="#">CCC</a>
<button id="getResult">Get result</button>
<div id="result"></div>

Now, when the button is pressed, I want to get the text from 3 links and insert them to the result div. Here is my code:

<script type="text/javascript">
    $(function() {
        $('#getResult').click(function() {
            var links = $('a');
            $.each(links, function() {
                $('#result').append('<p>' + links.html() + '</p>');
            });
        }); // end click
    }); // end ready
</script>

I expect the result would be

AAA
BBB
CCC

But it is

AAA
AAA
AAA

Does anyone know why and how to fix this? If you have a better way to do this, could you tell me? I'm very new to jQuery. Thank you for your help.

like image 386
Triet Doan Avatar asked Dec 01 '25 06:12

Triet Doan


1 Answers

Inside your .each function you call links.html() which only gets the html of the first element in the collection. You mean to use $(this).html() (probably).

http://jsfiddle.net/ExplosionPIlls/xZymh/

By the way you could rewrite this to just use the .html method itself to do the appending:

$("a").html(function (_, html) {
    $("#result").append("<p>" + html + "</p>");
});

http://jsfiddle.net/ExplosionPIlls/xZymh/1/

like image 136
Explosion Pills Avatar answered Dec 03 '25 18:12

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!