Search code examples
javascriptjqueryattrrangy

Why am I returned undefined?


I am wanting to get an attribute of the parent element that my cursor is inside of.

I have been totally unsuccessful for about two hours now, so I'm posting to see if anybody has any suggestions. This is the function I have but don't know why parentID only returns undefined:

function getAttrOfParent() {
    var newRange = rangy.getSelection().getRangeAt(0);
    var parentElement = newRange.commonAncestorContainer;
    var parentID = $(parentElement).attr('id');
    alert(parentID);
}

This works fine to get the text of the parent element...

function getTextOfParent() {
    var newRange = rangy.getSelection().getRangeAt(0);
    var parentElement = newRange.commonAncestorContainer;
    var parentText = $(parentElement).text();
    alert(parentText);
}

...and this works fine to get the title of a specified element.

function getAttrOfElement() {
    var parentID = $('#1').attr('id');
    alert(parentID);
}

Here's my jsFiddle, you have to click inside of the text area for the first two functions to work.


Solution

  • parentElement = newRange.commonAncestorContainer isn't giving you the parent element, it is giving you the parent node.

    This is fairly obvious if you console.log(parentElement) to see what is being selected.

    If you select text entirely inside one of your spans (which have ids) then you get the text node (which doesn't have an id).

    If you select more text, you get the paragraph element node (which doesn't have an id).

    You might want to try something like var parentElement = $(newRange.commonAncestorContainer).parents('span');