tags:

views:

37

answers:

3

I need to verify is the next element of each <a> tag <img> or not? so, i need to get the tagName of each <a> element's next tag.

$("a").each(function()
{
     how to verify it here?
});

Thanks

+4  A: 

jAndy's answer is correct and most efficient, but you can also use jQuery's is() method:

$('a').each(function() {
    if($(this).next().is('img')) { ... }
});
Tatu Ulmanen
+1  A: 
$("a").each(function(){
    if(this.nextSibling && this.nextSibling.tagName && this.nextSibling.tagName.toLowerCase() == 'img'){
        //so something when the next element is an image
    }
});

Edit: added check for element: if there is not nextSibling, it would fail. Text nodes doesn't have a tagName, so check for it too.

Lekensteyn
This is the direct approach in JavaScript.
Lekensteyn
-1 GOod JavaScript code, but not using jQuery, which simplifies it alot.
Tomas
Tomas, avoiding jQuery should not be frowned upon as it usually results in more efficient code and in this case I would personally use native JavaScript.
Tatu Ulmanen
A: 

If you're using the .tagname property on the DOM object, beware that In XHTML (or any other XML format), the element will be returned in lower case (e.g. 'img') In HTML you will get it in uppercase (e.g. 'IMG').

See https://developer.mozilla.org/en/DOM/element.tagName

You'll need to know this for your comparison.

James Wiseman