1

I have this code that checks if an img src is empty:

 if (document.getElementById('featuredIconImage348790').src == "") {
 document.getElementById('featuredIconImage348790').style.display = 'none';
  }

The src is empty but the code does not hide the image? Is there a problem that I missed?

5
  • Remove the == "" part and see what happens. Is 'featuredIconImage348790' really the HTML id attribute for that image? Is that even an image? HTML please. Commented Nov 25, 2015 at 0:01
  • 2
    Can you show an HTML example / jsFiddle? Commented Nov 25, 2015 at 0:01
  • 2
    console.log(document.getElementById('featuredIconImage348790').src)? Commented Nov 25, 2015 at 0:03
  • Ah, does that image element exist at the time you run the script? If not, you probably have an error in your console waiting to be read Commented Nov 25, 2015 at 0:03
  • @ERN check the answers bellow, if the answer help vote it up, if the answer is really what you loking for mark it as accepted answer. Commented Nov 25, 2015 at 9:08

2 Answers 2

2

Try to use getAttribute() instead :

if (document.getElementById('featuredIconImage348790').getAttribute('src') == "" ){
     document.getElementById('featuredIconImage348790').style.display = 'none';
}

When you have no src attribute like :

<img id="featuredIconImage348790" />

You have to make condition like == null because getAttribute() method will return null.

And if you have empty src attribute like :

<img id="featuredIconImage348790" src=""/>

You can make condition that check if empty == "".

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Wasn't sure why this made a difference until I saw the other answer. +1
1

The src of the img is considered to be relative - in this case a relative empty string, so it becomes prefixed with the hostname, as the snippet below demonstrates. Try getAttribute('src').

document.write('"' + document.getElementById('featuredIconImage348790').src + '"');
document.write('<br>');
document.write('"' + document.getElementById('featuredIconImage348790').getAttribute('src') + '"');
<img id="featuredIconImage348790" src="" />

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.