How to get the parent element type only for elements that have title attributes?

时间:2016-04-04 18:50:43

标签: jquery

I am trying to achieve the following to request for only anchor elements with title attributes, to tell me what their parent elements are:

var mtype =  $(".my-selectors").find("a").prop("title").parent().prop('nodeName');
console.log(mtype);

index.htm:563 Uncaught TypeError: $(...).find(...).prop(...).parent is not a function

What I am doing wrong?

2 个答案:

答案 0 :(得分:2)

You only need a simple has attribute selector.

var mtype = $('.my-selectors a[title]').parent().prop('nodeName')

Although, keep in mind, as is, this will only grab nodeName property for the parent of the FIRST one it finds.

A more specific, and possibly better move might be:

$('.my-selectors a[title]').each(function(i) {
    if ($(this).parent().length) { // should always have be true, but ...
        var mtype = $(this).parent().prop('nodeName');
    //  could also be defined with "= this.parentNode.nodeName;"
        console.log(mtype);
        /*  doWork  */
    }
});

答案 1 :(得分:1)

$('a[title]').each(function() { console.log(this.parentNode.nodeName) })