Kate Bishop
Kate Bishop

Reputation: 3

How to change link depending on div id?

I'm using Jcink Forums - I can style divs based on the user group which can be used as a html variable (for IDs).

How can I change the link based on the ID?

I'm assuming this cannot be done via just css and html however I'm not well-versed in JS

For Example (not the full code, just a really abridged version):

Stylesheet:

#admin .avatar {background-image:url("admin.jpg");}
#mod .avatar {background-image:url("mod.jpg");}

HTML:

<div id="<!-- |g_id| -->">
    <a href="link changes based on div id">
        <div class="avatar"></div>
    </a>
</div>

Upvotes: 0

Views: 623

Answers (2)

ellipsis
ellipsis

Reputation: 12152

You can use setAttribute to set the link href according to the id

var ele=document.querySelectorAll("div");
Object.values(ele).forEach((e)=>{
if (e.getAttribute("id") == "abcd") {
  var link = e.querySelector("a");
  link.removeAttribute("href");
  link.setAttribute("href", "www.link2.com");
} 
})
<div id="abcd">
  <a href="link1">
    <div class="avatar">aa</div>
  </a>

Upvotes: 0

mplungjan
mplungjan

Reputation: 178151

If you can script, you can do something like (inline for demonstration, you can loop over all divs and change their links)

<div id="<!-- |g_id| -->">
  <a href="whatever" onclick="this.href=this.closest('div[id]').id=='xxx'?'zzz':'yyy'">
    <div class="avatar"></div>
  </a>
</div>

where an ID of xxx will set the href to zzz otherwise set it to yyy

Upvotes: 1

Related Questions