Neal Rogers
Neal Rogers

Reputation: 500

How to get jquery element-object parent from id variable

I'm missing something basic here (newish to JQuery). I have the id of an element ex an array and wish to get it's parent. but the parent object looks like a whole function declaration of some type, when I display it. What am I missing please. Thx

$.each(arr, function (){
    var thisElId = arr[i][0];
    alert(thisElId);  //correct
    var EnclSpanParentText = $('#' + thisElId).parents(".accordion-heading").text;
    alert("SpanParent " + EnclSpanParentText);
    if (EnclSpanParentText == "Read")

markup image

Upvotes: 1

Views: 115

Answers (2)

Negi Rox
Negi Rox

Reputation: 3912

first of all text() is a function not a property second you can use this .. as per my understanding.

 $.each(arr, function (i,o)
    {
        var thisElId = $(this);
          alert(thisElId);  //correct
          var EnclSpanParentText =thisElId.parent().text() ;
          alert("SpanParent " + EnclSpanParentText);

        if (EnclSpanParentText == "Read")

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1073968

Two things:

  1. You're using parents, which gives you the full ancestry of the element, not just its parent. It's not clear to me whether you meant to do that. If you're looking for its closest parent matching the given selector, use closest(...) or parents(...).first()

  2. You're not *calling text, you're just referring to it. To call it (since it's a function), you add () to the end.

So either

var EnclSpanParentText = $('#' + thisElId).parents(".accordion-heading").text();
// --------------------------------------------------------------------------^^
alert("SpanParent " + EnclSpanParentText);

or

var EnclSpanParentText = $('#' + thisElId).closest(".accordion-heading").text();
// ----------------------------------------^^^^^^^---------------------------^^
alert("SpanParent " + EnclSpanParentText);

or similar.

Upvotes: 1

Related Questions