fish man
fish man

Reputation: 2700

jquery if have html tag

I have some code, the p.words is hidden, I tried to make a judge, if next div has span tag, then show the p.words, else keep the css rule.

I use jquery.next and jquery.find to make a judge $(this).parent().next('.col').find('span'), but it will show all the p.words even the next div has no span tag

<style>
.words{display:none;}
</style>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
    $('.words').each(function(){
        if($(this).parent().next('.col').find('span')){
            $(this).css('display','block');
        }           
    });
});
</script>
<a>Voodoo
   <p class="words"> 1</p><!-- do not show -->
</a>
<div class="col">
   <ul>
      <li>ATI Rage128 Pro</li><!-- no span tag -->
   </ul>
</div>
<a>NVIDIA
   <p class="words"> GeForce2 MX</p><!-- show --> 
</a>
<div class="col">
   <ul>
      <li>
         <span>NVIDIA GeForce2 MX 400</span><!-- have span tag -->
      </li>
      <li>
         <span>ATI 9200SE</span>
      </li>
   </ul>
</div>    

Upvotes: 0

Views: 1845

Answers (4)

SeanCannon
SeanCannon

Reputation: 77956

Change

 if($(this).parent().next('.col').find('span')){

to

 if($(this).parent().next('.col').find('span').length > 0){

The result of $(this).parent().next('.col').find('span') is an array which may or may not be empty, but will always resolve to true in your condition.

Upvotes: 3

Clive
Clive

Reputation: 36957

You need to make a slight change to your if statement:

if ($(this).parent().next('.col').find('span').length > 0) {
   ...

http://jsfiddle.net/JMdC6/

Upvotes: 1

Jasper
Jasper

Reputation: 75993

This line is the culprit:

if($(this).parent().next('.col').find('span')){

If there are no <span> tags found this will not return false (it will return an empty jQuery object). Try adding .length to the end of your selector; which will return 0 if the jQuery object is empty (0 is truthily equal to false):

if($(this).parent().next('.col').find('span').length){

Here is a jsfiddle of the above change to your code: http://jsfiddle.net/qfqJZ/

Upvotes: 1

JSager
JSager

Reputation: 1430

I think you can vastly simplify your code with this:

http://api.jquery.com/next-siblings-selector/

Also, I think the source of your problem is that find returns an empty array which does not evaluate to "false". Try this code:

if ($.find("doesnotexist")){console.log("Hi")}

Upvotes: 1

Related Questions