Adding View Details Button with JS

1.2k Views Asked by At

I'm trying to add a view details button to each product using JS. I want it to look for each instance of the class "clsItemBlock" and then append the html inside of clsItemPublished" The code below is adding multiple buttons on the first product, instead of one one each.

In a PERFECT world, since I know there are only 15 products per page, I could have it only check 15 times to prevent it from looping constantly.

MY JS:

 var divs = document.getElementsByClassName('clsItemBlock');
 for (var i = 0; i < divs.length; i++)
 {
 var iDiv = document.createElement('div');
 iDiv.id = 'detail_button';
 document.getElementsByClassName('clsItemPublished')[0].appendChild(iDiv);
 iDiv.innerHTML = '<a href="http://www.google.com">View Details</a>';
 }

FIDDLE:

http://jsfiddle.net/ptc6ws9o/1/

2

There are 2 best solutions below

1
On

Or, if it is appropriate you can just use details and summary tags: http://jsfiddle.net/dorgLr71/

<details>
    <summary>View Details</summary>
    <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin 
        dapibus porttitor libero, eget rutrum nibh laoreet et. 
        Pellentesque porttitor erat ligula, id elementum est egestas 
        eget. Mauris gravida dui ut leo tempor, nec placerat tortor 
        hendrerit.
    </p>
</details>
0
On

GOT IT!

 var divs = document.getElementsByClassName('clsItemBlock');
 for (var i = 0; i < divs.length; i++)
 {
 var iDiv = document.createElement('div');
 iDiv.id = 'detail_button';
 document.getElementsByClassName('clsItemPublished')[i].appendChild(iDiv);
 iDiv.innerHTML = '<a href="http://www.google.com">View Details</a>';
 }