$ .fn.data - jQuery

0

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

$('#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><divclass="content">
    <ul id="minhaLista">
        <li>Primeiro item</li>
        <li>Segundo item</li>
    </ul>
</div>
    
asked by anonymous 29.08.2018 / 18:15

1 answer

0

The $.fn.data function is for you to add or retrieve general data 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: link

In your code, in addition to the lack of the selector with # pointed to by @Ricardo Pontual , it also lacks within% with <li> with class div , which it searches for content and currently does not find, not putting anything in the element's custom data.

I set the script and its HTML so that it has a $li.find('div.content'); with the required class in 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><divclass="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>
    
29.08.2018 / 20:27