enars
enars

Reputation: 15

getElementById() display from several variables

I want to display via document.getElementById from an external javascript file a compilation of links to social networks depending on the language version of my website. The problem is it works perfectly for the first ID ("sociallv") but doesn't work for others ("socialen" and "socialru") if I use them separately on a webpage. What should I change?

/* Social networks start */

var start = "<div class='social justify-content-between'>"

var end = "</div>"

var facebook = "<a href='https://www.facebook.com/maggitekstils.lv' title='Facebook' rel='noreferrer' target='_blank'><div class='social-button facebook'></div>"; 

var draugiem = "<a href='https://www.draugiem.lv/maggitekstils.lv' title='Draugiem' rel='noreferrer' target='_blank'><div class='social-button draugiem'></div>"; 

var youtube = "<a href='https://www.youtube.com/channel/UC2H9dhm1Nzw3i4wveNTgHnQ/playlists' title='YouTube' rel='noreferrer' target='_blank'><div class='social-button youtube'></div></a>"; 

document.getElementById("sociallv").innerHTML = start + facebook + draugiem + youtube + end;

document.getElementById("socialen").innerHTML = start + facebook + youtube + end;

document.getElementById("socialru").innerHTML = start + facebook + youtube + end;

/* Social networks end */
<div class="social-media" id="socialen"></div>

Upvotes: 0

Views: 69

Answers (2)

miron
miron

Reputation: 1450

Did you check if there are any errors in your JS Console ?

For Chrome: https://developers.google.com/web/tools/chrome-devtools/open

For Firefox: https://developer.mozilla.org/en-US/docs/Tools/Web_Console

I supspect that the execution of your Javascript is abborted because you're trying to set a value for a property on an object which does not exists and therefore the blocks

document.getElementById("socialen").innerHTML = start + facebook + youtube + end;

document.getElementById("socialru").innerHTML = start + facebook + youtube + end;

are never reached. You should always do a check if the queried element exists or not:

// ...

if ( document.getElementById("socialen") ) {
  document.getElementById("socialen").innerHTML = start + facebook + youtube + end;
}

// ...

Upvotes: 1

Sean
Sean

Reputation: 827

In the html provided, you only have an element with id socialen which is why when you set the innerHTML of socialen it works. However socialru and sociallv aren't html elements therefore its not actually setting anything.

If you add the following to your html, you should get the expected result

<div class="social-media" id="sociallv"></div>
<div class="social-media" id="socialru"></div>

Upvotes: 1

Related Questions