Pergunta

I'm using jQuery to get the content of a link and want to replace the link with just the content it has.

I got it to work, but I'm wondering if I could write it in just one statement instead of two.

Here is my code:

text = $(this).closest('.ui-btn-text').find("a[data-rel='popup']").html();
$(this).closest('.ui-btn-text').find("a[data-rel='popup']").replaceWith(text);

Thank you!

Foi útil?

Solução

The .replaceWith() function accepts a function which returns the new HTML to replace that element with, so you could do:

$(this).closest('.ui-btn-text').find("a[data-rel='popup']").replaceWith(function() {
    return $(this).html();
});

It's important to note that this inside the function passed to .replaceWith() is different to this at the beginning of the line; inside the function it refers to the current matched element being replaced by the new HTML.

Outras dicas

You can optimize it like

textObj = $(this).closest('.ui-btn-text').find("a[data-rel='popup']");
textObj.replaceWith(textObj.html());
var node = $(this).closest('.ui-btn-text').find("a[data-rel='popup']");
node.replaceWith(node.html());
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top