Selecting the src of an input using ID in JQuery

3
if(!$("#src-img[src='']")){

}else{

};

I would like to know what is wrong with this selection in if, in case, I want, if a value is set in the src attribute, it executes if, otherwise else.

* That's why I put the '! '

    
asked by anonymous 22.12.2016 / 17:58

3 answers

2

If I understand correctly, what you are looking for is whether or not a given element with the id #src-img has an attribute src assigned. For this you can use different selectors.

Example to clarify:

['#src-imgA', '#src-imgB', '#src-imgC'].forEach(function(id) {
    console.log(id);
    console.log(!!$(id).attr('src'));
    console.log(!!$(id + "[src]").length);
    console.log('-------');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><imgid="src-imgA" />
<img id="src-imgB" src="" />
<img id="src-imgC" src="/o/meu/url" />

The commented result:

#src-imgA
false     // o elemento existe, mas o atributo "src" está vazio/não existe
false     // o elemento existe mas como não tem atributo "src" o seletor falha
-------
#src-imgB
false     // o elemento existe mas o atributo "src" está vazio
true      // o elemento existe e tem um atributo "src" (ele não verifica se está vazio)
-------
#src-imgC
true
true
-------
    
22.12.2016 / 19:01
5

You could use .attr like this:

if($('#img').attr('src') != ""){

}

In this way it will check if the src attribute of its image element is not empty and if not, if it is true, otherwise it can put an else.

    
22.12.2016 / 18:09
3

When jQuery does not find any element, it comes with an empty% object. This is not considered logically false by javascript, so the code you posted is equivalent to:

if (true) {
}

What you can do is take a look at the arraylike property of the jQuery return. If you did not get any element, length would be zero. Then you can compare ...

if ($("blablabla").length !== 0) {
}

Or use direct length, since zero is considered logically false.

if ($("blablabla").length) {
}
    
22.12.2016 / 18:02