$.fn.data - jQuery

Asked

Viewed 39 times

0

Well, I’m banging my head on this code, I’m reading a book about jQuery, but I can’t make this code work, someone can give a hint on how to solve it, and what this method works for ($.fn.data).

$('#minhaLista li').each(function(){
    var $li = $(this),
        $div = $li.find('div.content');
    $li.data('contentDiv', $div);
});
var $primeiroLi = $('minhaLista li:first');
$primeiroLi.data('contentDiv').html('new content');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
    <ul id="minhaLista">
        <li>Primeiro item</li>
        <li>Segundo item</li>
    </ul>
</div>

  • "minhalista" is an ID, the correct would not be var $primeiroLi = $('#minhaLista li:first');?

  • well, so far so good, but what is the relation of $.fn.html() as a Setter in the code, "new content" should not have appeared in the list?

  • After the last edit it seems that the script is working normally.

  • yes, I got it. Thank you!

  • Put it as an answer and not in the question. I reversed the edition of the Question, now just you formulate an answer explaining in detail where it failed ;)

Show 1 more comment

1 answer

0

The function $.fn.data serves for you to add or recover data in general of the element in question. It is widely used by other libraries and plugins, such as Bootstrap.

For more information, you can see in the documentation: https://api.jquery.com/data/

Already in your code, in addition to the lack of selector with the # pointed by @Ricardo Pontual, also missing within the <li> one div with class content, that he seeks in $li.find('div.content'); and currently does not find, not putting anything in the custom data element.

I adjusted the script and its HTML for it to have one div with the required class on both list items, so you’ll see the script work.

$('#minhaLista li').each(function(){
    var $li = $(this),
        $div = $li.find('div.content');
    $li.data('contentDiv', $div);
});
var $primeiroLi = $('#minhaLista li:first');
var $oDiv = $primeiroLi.data('contentDiv');
$oDiv.html('new content');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="content">
    <ul id="minhaLista">
        <li>Primeiro item <div class="content">div 1</div></li>
        <li>Segundo item <div class="content">div 2</div></li>
    </ul>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.