Man_E
Man_E

Reputation: 81

How to replace the content of the parent div with jQuery

i have this html code:

<div id="ht_key" class="ht_all">
    <div class="ht_bottom">
        <div class="ht_bottom_p">
            <span class="ht_bottom_o">
                <a href="javascript:;" onclick="htrc('key');\">click</a>
            </span>
        </div>
    </div>
</div>

This code may be seen in the page 5-6 times(or more). I want from the htrc function to replace the #ht_key div with some other content. ("key" is different in each case). The problem is that if in the page there are 2 divs with same "key" then when the htrc function takes place, then only the first #ht_key div is replaced. So since i need to replace the content of the #ht_key div where the a (from which the htrc function is called) was clicked, is there any way to replace its parent div(the parent div which has id)?

I have tried both parent and closest but none of these returned the result. Do you have any suggestion?

Thanks!

Upvotes: 4

Views: 1495

Answers (2)

Roman Bataev
Roman Bataev

Reputation: 9361

I assume #ht_key is actually a parent for an anchor (in which case you are missing closing tag in your snippet). I would remove "onclick" and bind the event handler like this:

$("span.ht_bottom_o a").click(function(){$(this).closest(".ht_all").html(...)});

Upvotes: 2

user113716
user113716

Reputation: 322492

My suggestion would be to make the ht_key a class instead of an id.

<div class="ht_key ht_all">

This way your HTML is valid.

Or change the onclick to pass this, and do a closest() up to ht_all:

<a href="#" onclick="htrc(this);">click</a>

js

htrc( el ) {
    $(el).closest('.ht_all');
    // ...
}

If you take this approach, the I'd use a HTML5 data- attribute for the ht_key:

<div data-key="somekey" class="ht_all">

And if you're using the latest versions of jQuery, you can do:

htrc( el ) {
    var $all = $(el).closest('.ht_all');
    var key = $all.data('key');
}

Upvotes: 5

Related Questions