Sweely
Sweely

Reputation: 396

Assign the element name to a variable?

So this is my example HTML:

<div name="John Doe"></div>

Note: I know all about ID's and classes in CSS. I am fully aware they exist. But in this case I'm wondering what to do when it's the name value I'm trying to work with.

Basically, how do I save the name of the div, in this case "John Doe" to a variable?

I can successfully access it with the below code:

$(document).ready(function(){
    $('div[name="John Doe"]').click(function(){

    Do something;

};

Upvotes: 0

Views: 66

Answers (3)

SeanCannon
SeanCannon

Reputation: 77956

You should use data attributes for this

HTML:

<div data-name="John Doe">...</div>

JS:

$(function(){
    $('div[data-name="John Doe"]').on('click', function() {
        var myNameVar = $(this).data('name'); // Here is your variable.
    });
});

http://jsfiddle.net/6tatB/

Upvotes: 3

Alex
Alex

Reputation: 35409

Element names cannot contain spaces. I took the liberty of adding an underscore:

$(document).ready(function(){
    $('div[name="John_Doe"]').click(function(){
        var divAttrName = $(this).attr('name').replace('_', ' ');;
    });
};

Upvotes: 1

Brett Gregson
Brett Gregson

Reputation: 5913

You can't have a space in the attribute name, but this will work

$(document).ready(function(){
    $('div[name="John Doe"]').click(function(){
        var divname = $(this).attr("name");
    }
};

Upvotes: 2

Related Questions