Search code examples
jqueryjquery-svg

Is it possible to find the parent or next / prev sibling of an SVGTSpanElement


I can normally find the parent or appropriate sibling of the event target using something like

$(".occupancy").bind("click", function(event){
    day = $(event.target).parent().attr("class");
    // more stuff
});

But if the event is triggered on an svg object for example

$(".booked").on("click", function(event) {
    day = $(event.target).parent().attr("class");
    $("#cancellation_Form_Wrapper").css("visibility","visible");
    $("#cancellation_Form_Wrapper").change();
}).svg({loadURL: '../_public/_icons/booked.svg'});

parent is undefined.

I appreciate that the svgdom varies from the normal DOM and have implemented jquery.svgdom.min.js. But I am not interested in the internal DOM of the SVG I am interested in where the SVG sits within the DOM.

I have tried to add a wrapper to the svgdom and then look for the parent of the wrapper. But that didn't work either. Any clues as to how this may be achieved?


Solution

  • OK At last I think I have got a reasonable answer. This probably not going to be expressed in techy speak but hopefully you will get the drift.

    It's not a perfect answer because you have to know or make an assumption about the dom. But it does work for me as my dom structure is fixed in this instance.

    I am not looking for the tagNames I am looking for the classes of the parents and siblings. So if something more generic is required you would have to refine this further.

    Find the element you are seeking by it's class using parentsUntil($(".wrapper").parent() you need this format as parentsUnitl() can't find itself. map this to create a string then use split to convert the string to an array find the last element in the array and you have the parent.

     $('.svgload').on('click', function(event) {
             alert('clicked svg new');
             var parentElements = $(event.target).parentsUntil($(".wrapper").parent())
                 .map(function () { 
                     return this.className; 
                 })
                 .get().join(", ");
             alert(parentElements);
             parentsArray = parentElements.split(",");
             alert(parentsArray.pop());
     }).svg({loadURL: '../_public/_icons/booked.svg'});
    

    I can't think how to find siblings yet I will probably work down from the found parent.

    I will report back if I find a way to do this.