AxxE
AxxE

Reputation: 833

jQuery .attr() returns "undefined" for existing attribute

I have been trying to access a custom attribute defined on a svg:rect DOM element using jQuery (v2.1.4). The exact element is below:

<rect id="lane2-diag_D" currentLane="2" class="draggableCircle" x="250" y="125" height="20" width="10" clr="Chartreuse" style="stroke: gray; stroke-width: 1px; fill: chartreuse;"></rect>

This element is cloned from another element and it's id is changed. I'm trying to access the attribute after adding it to an svg element on the page.

When I try to access the currentLane property using $('#lane2-diag_D').attr('currentLane') it returns undefined. If I try to access it with the javascript approach document.getElementById('lane2-diag_D').getAttribute('currentLane') it returns the correct value.

For all other element attributes jQuery returns their correct values.

What am I missing in the jQuery syntax?

Upvotes: 1

Views: 2700

Answers (2)

Yann Papouin
Yann Papouin

Reputation: 31

I fell on this thread before debugging the jQuery code to understand why $("item").attr("myVar") was returning undefined whereas $("item")[0].myVar was returning the right value. So I'm back to share my answer on this issue.

  • For jQuery<3.0, the library is always lower-casing the variable used in attr. So, if you try to access currentLane, then jQuery is trying for currentlane...

Source https://github.com/jquery/jquery/blob/2.2-stable/src/attributes/attr.js#L42

  • For jQuery >= 3.x, it looks like that this behavior has changed, so it should work correctly with these versions:

Source https://github.com/jquery/jquery/blob/3.x-stable/src/attributes/attr.js#L45

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You should place your code inside ready function and it will work, check example below.

Hope this helps.


$(function(){
  alert($('#lane2-diag_D').attr('currentLane'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<rect id="lane2-diag_D" currentLane="2" class="draggableCircle" x="250" y="125" height="20" width="10" clr="Chartreuse" style="stroke: gray; stroke-width: 1px; fill: chartreuse;"></rect>

Upvotes: 1

Related Questions