add link to all divs with a certain class

Here's hopefully a simple request. I just can't seem to get the mechanics of this working. I'm trying to find all divs with a certain class on a page and add an href to them. The code I have so far that doesn't seem to work is below.

function FBcheck() {
elements = document.getElementsByClassName('friend-icon');
for (var i = 0; i < elements.length; i++){
elements[i].href = "http://www.example.com";
}}
javascript

Answers

answered 3 months ago programtreasures #1

Actually you cant assign href property to div it should be assign to anchor element,

And other issue is you have used incorrect selector with ., use friend-icon selector instead of .friend-icon

see below is updated code snippet,

function FBcheck() {
      elements = document.getElementsByClassName('friend-icon');    
      for (var i = 0; i < elements.length; i++){
              elements[i].href = "http://www.example.com";
      }}
FBcheck() 
<a class="friend-icon">1</a >
<a class="friend-icon">1</a >
<a class="friend-icon">1</a >
<a class="friend-icon">1</a >
<a class="friend-icon">1</a >

answered 3 months ago Shc Final Judgement #2

Thank you to all of you for pointing out that you can't add an href to a div! This code is doing what I need it to.

function FJcheck() {
elements = document.getElementsByClassName('friend-icon');
for (var i = 0; i < elements.length; i++){
var aTag = document.createElement('a'); 
aTag.setAttribute('href', \"https://www.facebook.com\"); 
aTag.innerHTML = \"FB Link\"; 
elements[i].appendChild(aTag);}}

comments powered by Disqus