admin管理员组

文章数量:1410712

how i can check in this code that the parent in loop is span or div.

$('a img, span img').each(function(n){
var c= $(this).parent();
console.warn(c)
});

i want to know if this possible to check that find the parent tag is span or anchor in html

how i can check in this code that the parent in loop is span or div.

$('a img, span img').each(function(n){
var c= $(this).parent();
console.warn(c)
});

i want to know if this possible to check that find the parent tag is span or anchor in html

how i can check in this code that the parent in loop is span or div.

$('a img, span img').each(function(n){
var c= $(this).parent();
console.warn(c)
});

i want to know if this possible to check that find the parent tag is span or anchor in html

how i can check in this code that the parent in loop is span or div.

$('a img, span img').each(function(n){
var c= $(this).parent();
console.warn(c)
});

i want to know if this possible to check that find the parent tag is span or anchor in html

Share Improve this question asked Jan 12, 2012 at 7:52 Anirudha GuptaAnirudha Gupta 9,3199 gold badges58 silver badges83 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

You can use is:

$('a img, span img').each(function(n){
    var c = $(this).parent();
    if(c.is("span, a")) {
        //It's a span or an anchor!
    }
});

The is method returns true if any of the selected elements match the selector. In this case, the selected element is the parent, and the selector looks for either a span or an a element.

Alternatively, you could use parent with a selector and check the length of the resulting object:

$('a img, span img').each(function(n){
    if($(this).parent("span, a").length) {
        //It's a span or an anchor!
    }
});

The is method is marginally faster though (don't be misled by the apparently huge difference... the numbers are both quite low):

$(this).parent().is(/* selectors */);

Well you can get the tagname, as:


$('a img, span img').each(function(n){
  a = $(this).parent();
  console.log(a[0].nodeName)
});

Hope it helps

try

$(this).parents('div')<br/>
$(this).parents('span')<br/>

find parent div or span element

本文标签: javascripthow i can check that parent is span or anchor in htmlStack Overflow