简体   繁体   中英

How to change img src value using span tag

  • I want to change the img src value using the span tag element
  • I already get value for span tag but I can not find a way to change img src value
  • Problem is the span tag embedded inside the img src
  • To complete the src link span id value needed

  • I get span tag value using bellow function

    $('#icon').text(data.icon);

It will give output as

03n

so I want to update img src as

<img src="http://openweathermap.org/img/w/**span_value_shoud_be_there**.png"/>

I tried several way like this

<img src="http://openweathermap.org/img/w/<span id='icon'></span>.png"

But I can not get a solution. Appreciate your answers Thank you

I get span tag value using bellow function

Using jQuery text() with a parameter sets the text to that parameter value. You should use it without specifying a parameter to get the text of your <span> . Store that text in a variable and set your image's src attribute accordingly.

let text = $('#icon').text();
yourImg.src = `http://openweathermap.org/img/w/${text}.png`

In vanilla Javascript (not jQuery), if you have an image element:

<img class="my-image" src="" />

and you would like to give that image's src attribute a value, you can use:

<script>

  const myImage = document.getElementsByClassName('my-image')[0];      
  myImage.setAttribute('src', '[VALUE HERE]');

</script>

Further Reading:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM