Image based on the content of a div

Asked

Viewed 41 times

-1

I need to display an image based on the content of a div. The tag already exists and I need to discard the one that was loaded and replace it with the new tag with the image in question.

Let me give you an example, the site bears the artist’s name and the album cover, which is generated dynamically from an external site, for example:

<div class="ccartist">A Flock of Seagulls</div>
<div class="cover"><img src="blabla.bla/12345.jpg"></div>

I wanted to delete this img tag loaded by another page by following the parameters:

<div class="cover"><img src="patch/to/covers/{conteúdo da div ccartist}.jpg"></div>

Resulting in:

<div class="cover"><img src="patch/to/covers/A Flock of Seagulls.jpg"></div>

How I would do this using javascript/jquery?

Thank you!

1 answer

0

The best way to do this would be with Javascript.

Following example:

 <div class="ccartist">A Flock of Seagulls</div>
 <div class="cover"><img src=""></div>

<script>

//iniciando variáveis com o conteúdo de cada classe
var ccartist = document.getElementsByClassName('ccartist');
var cover = document.getElementsByClassName('cover');

//aqui você seta o conteúdo de ccartlist no atributo "src" do cover
cover.setAttribute('src', 'patch/to/covers/' + produtosIntTitulo[0].innerText + '.jpg');

</script> 

you can also use Jquery, which would look like this

<script>
 $(document).ready(function(){
   $('.cover').attr('src','patch/to/covers/' + $('.ccartist').text() + '.jpg');
 });
</script>
  • Hello friend, I edited the question, I forgot some details, for example the content is generated by an external JS, so I wanted to remove the tag loaded by another, with the parameters I suggested. I appreciate your help.

  • save Rodrigo. At what point do you want to replace the content? It was not clear, because with this code it will always overwrite the content of the img tag, but if it is at a specific time, clarify me so that I can edit the answer

  • I tried it in jsfiddle and it was ok, I tried it in Wordpress here and made some changes, not to give error in console: jQuery(Document). ready(Function($){ $('.cccover img').attr('src','patch/to/covers/' + $('.ccartist').text() + '.jpg'); }); It still didn’t work. I put the code before the </body>.

  • Is it like you see it for me on a test page here? http://radiover.co/teste/test.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.