Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the content of the parent div with jQuery

Tags:

jquery

parent

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!

like image 417
Man_E Avatar asked Oct 14 '25 04:10

Man_E


1 Answers

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');
}
like image 85
user113716 Avatar answered Oct 16 '25 20:10

user113716



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!