1

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);
 });
asked Apr 22, 2014 at 12:43

5 Answers 5

2

use .html() to set html.try this:

 $('.content h2').html('new sample');

Working Demo

answered Apr 22, 2014 at 12:44
Sign up to request clarification or add additional context in comments.

Comments

0

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'));
});

jsFiddle

answered Apr 22, 2014 at 12:47

1 Comment

Thank You, I actually wanted this code. Because I have same div class repeated twice, so this will replace only targeted div.
0

Use jQuery's .text()

$(".content h2").text("new sample");

FIDDLE

answered Apr 22, 2014 at 12:46

Comments

0

You can do that without jQuery:

var elem = document.getElementsByTagName('h2')[0];
elem.innerHTML = "New Value";
answered Apr 22, 2014 at 12:52

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.