Nicero
Nicero

Reputation: 4377

How to pass a dynamically generated ID to Jquery

I'm using a nice Jquery context menu which returns the ID of my element in the form

$(context).attr('id')

and not in the form

$(this).attr('id')

due to the fact that I'm using one single context menu for a large number of elements where each element has its unique ID. The context menu works perfectly as it executes the commands relative to the clicked element identified by its unique ID.

I use the context menu to write data to a MySQl db via $.get and this works too.

But now I would like to use the data I get back from $.get and use it with the .replaceWith method to change some text without refreshing the page:

$.get("jq_get_go.php", { parameter2: $(this).attr('menuCommand'), id: $(context).attr('id') }, 
    function(data) {
        $(".ci_saremo").xxxxx.replaceWith('<li class="Like ci_saremo" id="' + $(context).attr('id') + '"><a href="">' + data + '</a></li>');
    }
);

I don't understand what should I replace the xxxxx with to get the ID of my element that I know I have here

$(context).attr('id')

Of course if I omit xxxxx and leave

$(".ci_saremo").replaceWith('<li class="Like ci_saremo" id="' + $(context).attr('id') + '"><a href="">' + data + '</a></li>');

every ".ci_saremo" text will be replaced. So I need to identify it by its ID. Basically, I don't understand how to chain/insert $(context).attr('id') in the above string.

Upvotes: 2

Views: 1183

Answers (3)

swatkins
swatkins

Reputation: 13630

I may be misunderstanding your intentions, but it looks as if you're trying to replace the link text inside of the li item. If so, you should be able to do this:

$(context).
    .find(".ci_saremo")
    .replaceWith('<li class="Like ci_saremo" id="' + $(context).attr('id') + '"><a href="">' + data + '</a></li>');

The find method will grab the .ci_saremo elements within $(context).attr('id'). This should isolate the single element you want to change.

EDITED

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227200

If $(context).attr('id') returns the ID, doesn't that mean that context is your element?

If so, couldn't you just do this?

$(context).replaceWith('<li class="Like ci_saremo" id="' + $(context).attr('id') + '"><a href="">' + data + '</a></li>');

Upvotes: 0

paulmorriss
paulmorriss

Reputation: 2615

This should do it:

$('#'+$(context).attr('id')).replaceWith...

Upvotes: 3

Related Questions