Brian Millot
Brian Millot

Reputation: 189

Put something in my href

How is it possible to put something in data-notifications in jQuery?

See below my href which is composed like this:

<a href="#" class="OCnotifications" data-notification="">Notification (s)</a>

Upvotes: 0

Views: 67

Answers (1)

PSL
PSL

Reputation: 123739

You could use attr

$('.OCnotifications').attr("data-notification", "something");

or use the data API, which doesn't actually modify the attribute though, but you can use the data API to retrieve and set consistently on the element instead of using .attr if you are using .data.

 $('.OCnotifications').data("notification", "something");

Using the data API.

  • You can avoid doing DOM operations by accessing it using the attr.
  • Has support for vanilla JavaScript as well using dataset which is supported in newer browsers.
  • Any casting (conversion to numeric, parsing JSON to an actual object, etc.) are automatically handled in the data API. So you won't need to do them separately.

Also note that using .attr or .data as a getter will only get the attribute/data value of the first element in the collection if the selector matches multiple elements.

Upvotes: 3

Related Questions