简体   繁体   中英

How do I check if an A tag is wrapping around an IMG element?

Given an array of dom elements:

var arr = $("a");

How would you check, within a for loop, whether this A tag is wrapping around an IMG element?

arr[i].has("img")

Doesn't work because it is taking an array element.

A jQuery selector returns an array which is overloaded with a number of functions. By taking just one of those indexes you lose those functions. To work around this do:

  $(arr[i]).has("img")

This now results in an array that has jQuery's functions, but only contains the item you passed.

 var arr = $('a'); for (var i=0;i<arr.length;i++) { if ( $(arr[i]).find('img').length>0 ) { console.log('has img'); } else { console.log('has no img'); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a> <img/> </a> <a></a> 

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