Get value of a Custom Attribute using Javascript o

2019-01-11 08:57发布

问题:

How can I get the value of a custom attribute using javascript or jquery?

Like

<strong id="the id" original-title="I NEED THIS">

I've tried with .getAttribute() and attr()..(Javascrupt & jQuery) without success any idea?

回答1:

Don't use space in id.

And adding custom attributes make your html invalid. Use data-attributes instead:

<strong id="the_id" data-original-title="I NEED THIS">

$('#the_id').data('original-title');

http://jsbin.com/akoyut/2/edit



回答2:

Change "the id" to "the_id".

You can do it using plain javascript:

document.getElementById("the_id").getAttribute("original-title");


回答3:

Best Way to use like this:

jQuery(this).attr('original-title');


回答4:

a var DateofEvent = $('[data-original-title=I NEED THIS]').val();


回答5:

You can get the value by using the following syntax

$('#theid').attr('original-title');


回答6:

If you must use spaces in an id, retrieve the element and attribute value like this:

$('[id="the id"]').attr([some attribute string]);
//or
$('#the\\ id').attr([some attribute string]);

For custom attributes best use the HTML5 data-[somelabel] attributes, it's backward compatible and standardized. So in your case something like:

<strong id="the id" data-originalTitle="I NEED THIS">

Read more about data-attributes



回答7:

$('#the<remove space from here>id').attr('original-title');


回答8:

The following is an working example:

Javascript:

$(document).ready(function() {    
  var title = $("#the_id").attr("original-title");
}

Html:

<strong id="the_id" original-title="I NEED THIS"></strong>


回答9:

I did this as I needed it in a foreach

$(this).data('original-title')