Search code examples
javascriptjqueryeventstargetchildren

Using JQuery to get text of a div that's a child of a header to replace a different header


I'm trying to get the text contents of a .div('.child#') child of my event.target('h6.class'), and replace my other headers('h1.replacHeader#') using this script below...

$('h6.HeaderToBeClicked').click(function(event) { 
    var $target = $(this);
    $('.replaceHeader1').replaceWith("<h1 class='replaceHeader1'>" + $target.children(".child1").text() + "</h1>");
    $('.replaceHeader2').replaceWith("<h1 class='replaceHeader2'>" + $target.children(".child2").text() + "</h1>");
    });

});

HTML:
<div id="ReplaceTheseHeaders">
    <h1 class='replaceHeader1'></h1>
    <h1 class='replaceHeader2'></h1>
</div>
<div id="accordian" class="acc">
    <?php $counter = 1; ?>
    <?php foreach ($tmpl->vars as $var) { ?>
    <h6 class="HeaderToBeClicked"><a href="#">
    <div class="counter"><?php print $counter . "." ?></div>
        <div class="child1"><?php print $var['title'];?></div>
    <div class="child2"><?php print $var['name'];?></div>
    </a></h6>
<?php $counter = $counter+1; ?>
    <?php } ?>
</div>

I've noticed that .text() apparently doesn't apply to an event.target... So how could I go about achieving this?


Solution

  • If $target is intended to refer to the h6.class element, then you should change this line:

    var $target = $(event.target);
    

    to this:

    var $target = $(this);
    

    $(event.target) will actually refer to whatever descendant element was clicked. The event then bubbles up to the element that has the handler (h6.class) which is referenced with $(this).


    EDIT:

    If this is similar to your HTML, the code runs perfectly. If (for example) .child1 and .child2 are nested deeper inside h6.class, then we would need to change things up a bit.

    <h6 class='class'>
        <div class='child1'>this is child 1</div>
        <div class='child2'>this is child 2</div>
    </h6>
    
    <div class="replaceHeader1">header1</div>
    <div class="replaceHeader2">header2</div>
    <div class="replaceHeader1">header1</div>
    <div class="replaceHeader2">header2</div>
    

    EDIT 2:

    Given the HTML you posted, try the code below. Please note that you don't seem to have a closing tag for your <a href="#"> element. The code below should work either way though.

    $('h6.HeaderToBeClicked').click(function(event) { 
        var $target = $(this);
        $('.replaceHeader1').text( $target.find(".child1").text() );
        $('.replaceHeader2').text( $target.find(".child2").text() );
    });
    

    This assumes you're just change the content of your .replaceHeader elements. If you need to change the tag name as well, you'll need to go back to using replaceWith().