1

I'm trying to replace an HTML element i get via it's index, I'm trying this but it won't work:

<div class="results">
    <div id="61">Result 1 content</div>
    <div id="8762">Result 2 content</div>
    <div id="234">Result 3 content</div>
</div>

<script>
    var index = 0;
    var html = '<div id="243">Result 1 content</div>';
    var element = $('.results').get(index);
    element.replaceWith(html);
</script>

how can I replace an entire HTML element by getting it by it's index?

5
  • 2
    Why are you replacing an entire element just to change its ID? Commented Nov 4, 2012 at 21:47
  • 1
    Oh yea, just pollute the global namespace with all those variables. I'm sure nothing can go wrong. :P (Use a function wrapper, for crying out loud.) Commented Nov 4, 2012 at 21:51
  • this is just an example, I need to do it by each or via for depending by the situation, sometimes i get a list of results via JSON and i need to replace the elements starting by the 0 to the ##. In other cases i just need to update them in runtime. Commented Nov 4, 2012 at 22:01
  • I assume the element which you want to replace is a child of the .results element, if it is not or if you need help adapting the function to work with your use case give a holler. Commented Nov 4, 2012 at 22:05
  • get() will get the native DOM element, which does'nt have a replaceWith method as it's not a jQuery object. Commented Nov 4, 2012 at 22:25

4 Answers 4

4
$('.results div').eq(index).replaceWith(html);

Fiddle

You should use .eq() to filter the set of matched elements inside a jQuery object by its index. Also $('.results') only has 1 element (itself). I assume you're looking for the divs inside of it.


Also if you have divs inside of your divs, use the more specific child selector:

$('.results > div').eq(index).replaceWith(html);

Which has the same effect as using the .children method with a selector filter:

$('.results').children(':eq(' + index + ')').replaceWith(html);

Or more simply, concatenating it all in a single selector:

$('.results > div:eq(' + index + ')').replaceWith(html);

Fiddle

There are many other ways to get this done with jQuery, but these should be more than enough. =]

Sign up to request clarification or add additional context in comments.

Comments

1

.get retrieves the DOM element at the index. What you're looking for is .eq

Comments

0
var index = 0
$($('.results div')[index]).replaceWith('<div id="243">Result 1 content</div>')

Comments

0
var element = $('.results').find('div');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.