1

I am attempting to insert a url into the data-url using javascript, and I am getting nowhere since I have no clue what I am supposed to do

Here is my html example

<a class="button" data-url="http://www.google.com" href="#"></a>

all I have at the moment is within my javascript the following:

var link = {
    url: 'http:www.google.com'
  }

but now I don't know how to get link to be pushed inside the data-url="".

All help is much appreciated.

4 Answers 4

5

You can also use dataset like document.querySelector('a.button').dataset.url

Sign up to request clarification or add additional context in comments.

1 Comment

+1 As far as accessing the data set goes, I'll favor this over my own reply, but I still think href should be used even in a majority of cases where the author assumes it shouldn't.
3

Use getAttribute just like you would any other attribute:

var url = document.querySelector('a.button').getAttribute('data-url');

Before going down that route, though, I hope you've carefully considered storing the url in the href attribute instead, which will - depending on your use case - probably be preferable in terms of graceful degradation.

1 Comment

And to set a value you can do: $0.attributes['data-url'].value = 'https://example.com'
-1

You can use attributes property of element.

var data = $('[class="button"]')[0].attributes[1].value;
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="button" data-url="http://www.google.com" href="#"></a>

3 Comments

I don't feel comfortable with hard-coded [0]s and [1]s. As long as there are solutions which do not require to do it I'm going to do it the other way
If you're going to assume jQuery, you might as well go all the way and get $('.button').data('url');
@Sebastian: As for the [0], to be fair, other responses utilizing querySelector rather than querySelectorAll is still a hard-coded assumption that the first match should be grabbed. As regards the [1] on the attribute list, I'm entirely with you, though.
-1

Hi all many thanks to your input, it enlightened me as in how to complete this.

I did the following:

    var link = {
      url: 'http://www.google.com'
    };

    var el = document.querySelectorAll('a.button');

  el.forEach(element => {
    element.setAttribute('data-url', link.url);
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.