Mathieu Mathieu - 7 months ago 37
Javascript Question

Add data-attribute and its value to link with pure javascript

I have a javascript snippet that goes:

function(){
location.href = '<%= my_route %>';
}


It turns this into the html

<a href="myroute">a certain text i have no problem here</a>


I would like to add with javascript data-no-turbolink = true to the link so that i have in html

<a href="myroute" data-no-turbolink = true >a certain text i have no problem here</a>


I tried

function(){
location.href = '<%= my_route %>' location.data-no-turbolink = true;
}


but it does not work.

How to do this ?

Answer
location.setAttribute('data-no-turbolink', true) 

should do the trick. Dom API setAttribute