Jquery Custom Attributes

Jquery custom attributes

You can do this, use data- attributes though (part of the HTML5 specification), like this:

<li data-something="CommonLi"></li> 

jQuery even has built-in support for these in 1.4.3+, for example:

$("li").data("something") //"CommonLi"

For your other questions:

  • They'll validate if it's HTML5 - but won't break anything in HTML4
  • This shouldn't interfere with the designer, but it'll depend on which designer
  • If you're fetching from an element, the performance is the same as any other attribute

Get custom attribute value in Jquery?

Because you're alerting the result of .val() (and I'm not sure why you're using it) which is a jQuery object - you simply want the attribute:

var text = $(this).attr("data-overlay")
alert(text);

JQuery set custom attribute from value

On either way (inline or separate), you will require to set / change custom_attribute's value based on the change event of drop-down as following:

Inline:

<select id="myselect-name" my_attribute="1"
onchange="javascript: this.setAttribute('my_attribute', this.value);">
<option>1</option>
<option>2</option>
<option>3</option>
</select>

DEMO - 1

Separate:

<select id="myselect-name" my_attribute="1" class="myclass">
<option>1</option>
<option>2</option>
<option>3</option>
</select>

$('.myclass').change(function() {
$(this).attr('my_attribute', $(this).val());
alert($(this).attr('my_attribute'));
});

DEMO - 2

Selecting custom data attributes in JQuery

You are pretty close. You can use jQuery's .data() method to read attributes that start with data-. So in your case .data("value") since your attribute is data-value="some".

This should do it:

$('li[data-value]').each(function(){
alert($(this).data("value"));
});

Here is a working fiddle as well: http://jsfiddle.net/nuphP/

Add a custom attribute to an element in Jquery

You can't. Use jQuery.data api instead to associate custom properties with element's jQuery wrapper. http://api.jquery.com/jQuery.data/

is it possible to set custom attribute by jQuery attr() function using JS variables

I guess you should use this

jQuery('#div').attr(attname,attvalue);


Related Topics



Leave a reply



Submit