patrick
patrick

Reputation: 657

jQuery - best practises for defining variables

I am trying to define a variable by getting the attribute of an element. In addition to using the attribute I would like to add some html.

Is there a better way to do it then this?:

var tip = $(this).attr('title').append('<p>Take me to:</p>');

Upvotes: 0

Views: 78

Answers (4)

Pete Lada
Pete Lada

Reputation: 1318

$(this).attr('title') will return the title, which you are trying to append the html to (which wouldn't work).

var x = $(this).append(html).attr('title'); 

should work (x will equal the title of the element).

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 77996

I'd keep it simple, and keep it a jQuery object:

var $tip = $('<p>Take me to: ' + $(this).attr('title') + '</p>');

Upvotes: 0

DanRedux
DanRedux

Reputation: 9359

What you're doing is pretty undefined behaviour. attr(name) returns the value of that attribute as a string, number, whatever it is. So, you can treat it like any other value.

`var tip = '<p>Take me to: '+$(this).attr('title')+'</p>';

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

Something like this:

var tip = $('<p/>', {
    title: 'Take me to ' + $(this).attr("title")
});

Upvotes: 1

Related Questions