Johnathon64
Johnathon64

Reputation: 1320

cannot get id of parent

I am trying to get the ID of the event targets parents parent, however it comes back as undefined, but I know for a fact the ID does exist as I have used firebug to confirm this.

Here is my html markup:

<div class="grid-stack-item ui-draggable ui-resizable ui-resizable-autohide" data-gs-x="0" data-gs-y="0" data-gs-width="4" data-gs-height="4">
        <div class="grid-stack-item-content ui-draggable-handle" id="chart"></div>
        <div class="overlayed" data-render="" data-chartType="" data-devID="" data-metricType="" data-refresh="30000" data-title="" data-subtitle=""
                    data-yAxis="" data-tooltip="" data-lineWidth="0.5" data-timeWindow="10">
            <span class="glyphicon glyphicon-pencil panel-icons chart-edit" style="padding-right: 10px"></span>
            <span class="glyphicon glyphicon-zoom-in panel-icons"></span>
            <span class="glyphicon glyphicon-trash panel-icons"></span>
        </div>
    </div>

and here is my javascript/jquery for trying to get the id

$('.overlayed').on('click', '.glyphicon-pencil', function (e) {
    e.preventDefault();
    e.stopPropagation();
    alert("what is going on!");
    //hold the overlayed element for later use
    var overlayedData = $(this);
    var chartID = $(this).parent().parent().attr('id');

    $('#editWidgetModal').modal('toggle');
}

Upvotes: 1

Views: 60

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337590

The parent().parent() of .glyphicon-pencil is the .grid-stack-item element, which has no id. I assume you're attempting to target the #chart element, seen as it's the only one with an id in your HTML sample. If this is the case, your code fails as that element is a sibling of the parent element. In which case you can use prev() to get it. Try this:

var chartID = $(this).parent().prev().prop('id');

Or:

var chartID = $(this).closest('.overlayed').prev().prop('id');

Working example

Upvotes: 3

Related Questions