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

5 Answers 5

2

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

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

Working Demo

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

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

Comments

0

You can do that without jQuery:

var elem = document.getElementsByTagName('h2')[0];
elem.innerHTML = "New Value";

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

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.