You can use closest
for that:
$(window.getSelection().getRangeAt(0).endContainer).closest("[id]").attr("id");
closest
finds the first element matching the given selector, starting with the current element and then looking at ancestors. The selector [id]
matches an element that has an id
attribute.
Or if for some reason you want to do it without jQuery:
var parent = window.getSelection().getRangeAt(0).endContainer;
var newpargId = parent.id;
while (!newpargId && parent && parent.nodeName.toUpperCase() !== "BODY") {
parent = parent.parentNode;
newpargId = parent.id;
}