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?
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 thedivs inside of it.Also if you have
divs inside of yourdivs, use the more specific child selector:Which has the same effect as using the
.childrenmethod with a selector filter:Or more simply, concatenating it all in a single selector:
Fiddle
There are many other ways to get this done with jQuery, but these should be more than enough.
=]