1

I know this may look like a repost, but I am not able to get the code to work that the community made here.

What I am trying to do is make an array of all the classes listed in the element I am clicking on.
The element I am clicking on is a <g></g> element from a SVG object.

I would like to post the classes (in an array) to a modal and the ID of the <g> element. Here is my code:

//reveal Modal when when clicking on an item box.
$(document).ready(function() {
    $('.items').click(function() {
        $.ajax({
            type: "POST",
            url: "/includes/functions/choose_item.php",
            data: { id: this.id, class: this.className}
        })
            .done(function() {
                $('#choose_item_modal').foundation('reveal', 'open', "/includes/functions/choose_item.php") ;
            })
    });
});

It post it to my PHP script, and the ID works, but the class is in an array of baseval and animval, and I would like an array of all values of the baseval only.

This is the array I get:

Array ( [animVal] => items hero_item [baseVal] => items hero_item )

Thanks for any help.

Community
  • 1
  • 1
Oliver Nybroe
  • 1,828
  • 22
  • 30

1 Answers1

2

SVG elements doesn't really have classes like regular elements, and the className property returns a special object, usually a SVGAnimatedString looking like

{animVal: "class class2", baseVal: "class class2"}

The class attribute is really just a regular attribute with some strangeness, so you need to use getAttribute('class') instead, or in jQuery attr() to get the value of the attribute

$(document).ready(function() {
    $('.items').click(function() {
        $.ajax({
            type : "POST",
            url  : "/includes/functions/choose_item.php",
            data : { 
                id      : this.id, 
                'class' : $(this).attr('class')
            }
        }).done(function() {
            $('#choose_item_modal').foundation('reveal', 'open', "/includes/functions/choose_item.php") ;
        });
    });
});

note that class is a keyword in javascript, so it should be quoted.
If you need an array, you can do $(this).attr('class').split(/\s+/);

TEST

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Ah wauw thank you alot! That worked perfectly, and I did not know that about classes. Great thing that you explained that out. – Oliver Nybroe Dec 01 '14 at 19:05
  • SVG elements can have a class attribute just like any regular element, but it's true that it was exposed in a different way in the DOM (unfortunate historical mistake). I think the solution here is fine, an alternative that exists in most recent browsers is the newer API [`Element.classList`](https://developer.mozilla.org/en-US/docs/Web/API/Element.classList), it works the same on both svg and html elements. – Erik Dahlström Dec 08 '14 at 15:01