0

I have

<div class="test">hello everyone</div>

and I want to change each hello in this div with

<h1>helllo</h1>

for example I've used

$(this).text().replace("hello", "<h1>hello<h1>");

but it outputs

<h1>hello</h1>

I want it apply as HTML not as text how can I do it?

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
mohamd Agoumi
  • 80
  • 1
  • 11

5 Answers5

1

Your code is only replacing the text returned. That too it wont replace in the DOM, it will only be in javascript. So after replacing the text, render the returned value using .html()

var $myDiv = $('.test');
$myDiv.html($myDiv.text().replace("hello", "<h1>hello</h1>"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test">hello everyone</div>
Karthikeyan
  • 302
  • 1
  • 11
0

If you are interested in a pure JavaScript approach, you can use the innerHTML() property to replace your string with html like this:

var x = document.querySelector(".test");
x.innerHTML = x.innerHTML.replace("hello", "<h1>hello</h1>");
<div class="test">hello everyone</div>
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
0

.html() to access & change the html, regex to replace hello with <h1>hello</h1>

$(this).html($(this).html().replace(/hello/g,"<h1>helllo</h1>"));
hanshenrik
  • 19,904
  • 4
  • 43
  • 89
0

Hey I wanted to highlight a code in my div but since I didn't have a lot of time to do that I just used highlight.js to do that but I'm still looking for a good idea to do that

mohamd Agoumi
  • 80
  • 1
  • 11
-3

The code you have written for this replacement is perfectly nice but instead replacing a particular section, you are replacing complete div data

1.) Store div content to a variable e.g. var myDiv

2.) Replace desired content

3.) Put back replaced portion back to music

Example

jQuery(".test").html(function(){
      jQuery(this).text().replace("hello", "<h1>hello</h1>");
})
Prx
  • 1
  • 3
  • text() will html-encode the argument, the html will be `<h1>hello<h1>` - and you forgot to save the results anywhere.. and you don't use a regex to match every hello, just the first will be replaced. – hanshenrik Jan 06 '19 at 21:11