Home > Software engineering >  How to get the output of data attributes into a JavaScript variable?
How to get the output of data attributes into a JavaScript variable?

Time:12-17

I have a question about the following. I want to display a logo that changes every week by dynamic data. Below you see the code that generates the dynamic data.

<!-- Paste this where you want the article to appear --> 
<div 
    data-article="programma"
    data-param-teamcode="89678"
    data-param-gebruiklokaleteamgegevens="NEE"
    data-param-aantaldagen="100"
    data-param-eigenwedstrijden="JA"
    data-param-thuis="JA"
    data-param-uit="JA"
    id="clubcode1" data-fields="thuisteamclubrelatiecode" 
></div> 

<!-- This should be pasted once in the <head> for the best performance. If you already have jQuery included skip that script --> 
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> 
<script src="https://dexels.github.io/navajofeeds-json-parser/js/dist/feed-0.0.1.js"></script> 
<script> 
feed.init({ 
    clientId: "vbvEvjxCyc" 
}); 
</script>

When running the code above it generates three codes. The output of this code gives me: BBBC523, BBBC523 and BBBF79V. I need the first in the list for my other code to display a logo.

My other code looks like this:

<script>
    var link = "https://logoapi.voetbal.nl/logo.php?clubcode=";
    var clubcode2 = document.getElementById('clubcode1');
    var clubcode3 = clubcode2.getAttribute('data-fields');
    

    document.write("<img src="   "'"   link   clubcode3   "'");

</script>

The output that I need to display the logo of a football/soccer team looks like this:

document.write('<img src="https://logoapi.voetbal.nl/logo.php?clubcode=BBBC523"')

So I need to make a variable of the output of the dynamic data. From that output I need the first/first-child. I this case BBBC523. Can someone provide me the right steps/code to fix it?

Right now it got this <img src="https://logoapi.voetbal.nl/logo.php?clubcode=thuisteamclubrelatiecode" <="" div=""> but this is not good.

I searched hours on the internet to get a solution, but I'm still not successful. I like to see a solution for my problem.

CodePudding user response:

If you are just trying to display the logo, it seems you're just using the API wrong. I stumbled across this page that shows how to display a logo.

<!-- Paste this where you want the article to appear --> 
<div 
    data-article="clublogo"
    data-fields="clubdata.logo" 
></div> 

<!-- This should be pasted once in the <head> for the best performance. If you already have jQuery included skip that script --> 
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> 
<script src="https://dexels.github.io/navajofeeds-json-parser/js/dist/feed-0.0.1.js"></script> 
<script> 
feed.init({ 
    clientId: "vbvEvjxCyc" 
}); 
</script>

unfortunately StackSnippets don't work well with including js files like this so this is pasted as regular code

That gives you the logo based on that first clubcode.

However, if for some reason you are actually trying to do something else then you would probably want to use something like

let clubcode = document.querySelectorAll("#clubcode1 .string")[0].innerText

This would get the text inside of that first clubcode list that gets returned and added to the page.

Also, using document.write() is something that should be avoided and typically you would use something like .createElement() and .append() to add new elements to the page dynamically.

EDIT

Here I have a jsfiddle that dynamically loads the logos based on what the API returns to the page. I have included that jsfiddle to show that the code works because Stack Snippets do not seem to like the external <script> includes.

const _ElementAwait = el => {
  return new Promise(resolve => {
    if(document.querySelector(el)) return resolve(document.querySelector(el))

    const observer = new MutationObserver(ml => {
      if(document.querySelector(el)) {
        resolve(document.querySelector(el))
        observer.disconnect()
      }
    })

    observer.observe(document.body, { childList: true, subtree: true })
  })
}

const _AddLogo = i => {
  let clubcode = document.querySelectorAll("#clubcode1 .string")[i].innerText
  
  const logo = document.createElement("img")
  logo.src = `https://logoapi.voetbal.nl/logo.php?clubcode=${clubcode}`
  logo.alt = clubcode
  document.body.append(logo)
}


_ElementAwait("#clubcode1 .string").then(el => {
  _AddLogo(1)
  _AddLogo(3)
})
<!-- Paste this where you want the article to appear --> 
<div 
    data-article="programma"
    data-param-teamcode="89678"
    data-param-gebruiklokaleteamgegevens="NEE"
    data-param-aantaldagen="100"
    data-param-eigenwedstrijden="JA"
    data-param-thuis="JA"
    data-param-uit="JA"
    data-fields="thuisteamclubrelatiecode" 
    id="clubcode1"
    style="display: none"
></div> 

<!-- This should be pasted once in the <head> for the best performance. If you already have jQuery included skip that script --> 
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> 
<script src="https://dexels.github.io/navajofeeds-json-parser/js/dist/feed-0.0.1.js"></script> 
<script> 
feed.init({ 
    clientId: "vbvEvjxCyc" 
}); 
</script>

To explain a little further, basically the API writes a <table> inside of the <div> we have on the page, with each row containing a different clubcode. And each code is inside of a <span> with a class of string, which we can used to specifically select those elements using .querySelectorAll().

The only other thing to note is that you need to wait for the API to return the codes and write them to the page, which is what the _ElementAwait() function is for. All this does is creates an observer that will return when an element finally exists on a page. It's just one way to do this but I find it to be a handy function for other things as well.

  • Related