3

Supposing I have the correct location of an element whats the best way to replace all the html including the tags of a given block of HTML code using jQuery()? I'm looking to do something similar to the following. Is this a good way to do this? What other ways are available or useful to know about?

var location = 'td[id^="A0.R0.Work"]';
var element = jQuery(location).prev();
element.html('<h1>some code</h1>');

Thanks.

1
  • what the the recommended way of updating the entire html tags included... the .html()? Commented Mar 8, 2012 at 5:36

3 Answers 3

2

Try .replaceWith()

$(element).replaceWith(other_stuff);
Sign up to request clarification or add additional context in comments.

4 Comments

Nice. Forgot about that one.
$("#JeffB.replaceWith_memory").replaceWith('boobs'); It's ok. I wish I were that lucky. ;)
I imagine I can also use .text(other_stuff) or .html(other_stuff) would that do the same thing?
No. .replaceWith() replaces the entire block (including tags). .text() and .html() only replace the content of the block.
1

The code you provide will try to assign the HTML to whatever jQuery's html function returns. Instead, pass your html as the argument to the html function:

var location = 'td[id^="A0.R0.Work"]';
var element = jQuery(location).prev();
element.html('<h1>some code</h1>');

2 Comments

You are correct about the usage of html(), but remember that it replaces the contents, i.e. the children of the element, not the element itself.
Ah, you're right--I read the question wrong. @SenorAmor's answer covers it nicely, though!
0

JQUERY is sometimes too much overhead.

var location = document.getElementById('A0.R0.Work');
location.innerHTML = '<h1>some code</h1>';

1 Comment

there is also document.getElementsByClassName()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.