Im using the below code to replace the text within the h1 tag, but its not getting effected. I want to replace "sample" to "new sample". I'm doing wrong?
<div class="content">
<h2>sample</h2>
</div>
var t = jQuery('.content');
t.children("h2").each(function() {
var contents = jQuery(this).contents();
jQuery(this).replaceWith(new sample);
});
5 Answers 5
answered Apr 22, 2014 at 12:44
Milind Anantwar
82.3k26 gold badges97 silver badges128 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
If you want to replace some part of content then try this:
jQuery('.content h2').each(function(i, v) {
$v = $(v);
$v.html($v.html().replace('sample', 'new sample'));
});
answered Apr 22, 2014 at 12:47
Manoj Yadav
6,6121 gold badge25 silver badges21 bronze badges
1 Comment
user3141537
Thank You, I actually wanted this code. Because I have same div class repeated twice, so this will replace only targeted div.
answered Apr 22, 2014 at 12:46
reggaemahn
6,7286 gold badges40 silver badges64 bronze badges
Comments
You can do that without jQuery:
var elem = document.getElementsByTagName('h2')[0];
elem.innerHTML = "New Value";
answered Apr 22, 2014 at 12:52
roshiro
7801 gold badge5 silver badges9 bronze badges
Comments
Set .text()
t.children("h2").text('new sample'));
If you want to set .html() content
t.children("h2").html('new sample'));
Child Selector ("parent> child")
$('.content > h2').html('new sample');
answered Apr 22, 2014 at 12:45
Tushar Gupta - curioustushar
57.2k24 gold badges106 silver badges110 bronze badges
Comments
default