简体   繁体   中英

Getting a data attribute from a javascript

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.

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.

您还可以使用像document.querySelector('a.button').dataset.url这样的数据集

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>

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);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM