Search code examples
htmljqueryjquery-selectors

How to use .html() to change content later in document


I need to rewrite the html in 2 <p> tags when I check a checkbox. Note: the <div class="summary"> container repeats many times based on output from a DB.

* HTML *

<div class="summary">
    <div>Data 1</div>
    <div>Data 2</div>
    <div class="col_5"><input type="checkbox" /></div>
</div>
<div class="details">
    <p>label:</p><p>info</p>
    <p>label 2:</p><p>more info</p>
    <p class="jQuery1">another label to be changed:</p><p class="jQuery2">final info to be changed</p>
</div>

* JavaScript (everything works except comments 1 & 2) *

$(document).ready(function(){
    $('input:checkbox').change(function(event) {
        $(this).closest('div.col_5').html('Yes');
        $('div.details').next('p.jQuery1').html('Changed 1'); // c1 -- this does not work
        $('div.details').next('p.jQuery2').html('Changed 2'); // c2 -- this does not work
    });
    $('.summary').click(function(e){
        if ($("input:checked").length == 0) {
            $(this).next('.details').slideToggle('slow');
        }
    });
});

Solution

  • The .next() method returns the next sibling of the element you call it on, but you are trying to find children of the element you call it on so you should use .children() (to retrieve only direct children) or .find() (to get descendants including children, grandchildren, etc.).

    Try the following:

    $('input:checkbox').change(function(event) {
        var $div = $(this).closest('div.col_5'),
            $nextDiv = $div.closest('div.summary').next('div.details');
        $div.html('Yes');
        $nextDiv.find('p.jQuery1').html('Changed 1');
        $nextDiv.find('p.jQuery2').html('Changed 2');
    });
    

    The reason I'm keeping a reference ($div) to the clicked checkbox's parent div is because you need it to find the div afterwards and you won't be able to use this after you've overwritten the div's html with the string 'Yes' since that deletes the element that this refers to.