J1293
J1293

Reputation: 71

Replace html string to img tag with pure javascript

I want javascript to do this:

According the word that is in the div, i want the string be replaced with a img tag.

if i have

<div id="example" style="align-content: right; text-align: right">abc</div> 

with `

<div id="example" style="align-content: right; text-align: right"><img src="example123.html"></div>`

But only if inside the div is the text/string "abc"

Another case, if i have

<div id="example" style="align-content: right; text-align: right">def</div>

i want to convert into this

<div id="example" style="align-content: right; text-align: right"><img src="anotherexample.html"></div>

As the similar of the 1st case, replace with another img in case of the text be "def".

I have done this with jquery,

This was my code done in jquery

$("#example:contains('abc')").html(function (_, html) {return html.replace(/abc/g, "<img src=example123.html>")});

$("#example:contains('def')").html(function (_, html) {return html.replace(/def/g, "<img src=anotherexample.html>")});

It was easy to do, but i have some problems using jquery in my work, so i can't and i shouldn't use jquery or another framework. It would be great if it was done in pure javascript.

I almost forgot that it would be great using conditionals, specially swith, i think using switch instead of if else could be less tangled

Thanks in advance for your answers.

PD: if you ask me why i need to solve this, the reason is that i am using an application that generates pdf files extracting the data from a DB, and according to the text, replace with the pics with a specific URL.

Upvotes: 0

Views: 1201

Answers (2)

ellipsis
ellipsis

Reputation: 12152

Try this. It iterates over all the div elements and checks their text using textContent.If it matches it replaces the text with image tag using innerHTML

var a = document.querySelectorAll('div');
a.forEach((e) => {
  if (e.textContent == "abc")
    e.innerHTML = "<img src='example123.com'>"
 if(e.textContent == "def")
    e.innerHTML = "<img src='anotherexample.com'>"
})
<div id="example" style="align-content: right; text-align: right">abc</div>
<div id="example" style="align-content: right; text-align: right">def</div>

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 371118

Because you're using an element with a particular id, it's unique - all you need to do is select that element and check to see if its innerHTML includes the string you're looking for. You could use a regular expression to replace all instances of abc or def with the appropriate tag:

const example = document.querySelector('#example');
const srcs = {
  abc: 'example123',
  def: 'anotherexample'
};
example.innerHTML = example.innerHTML.replace(
  /abc|def/g,
  prop => `<img src="${srcs[prop]}">`
);
<div id="example" style="align-content: right; text-align: right">before abc after</div>

Upvotes: 3

Related Questions