-1

here my code i just wanna change the innerHTML of btn by grabbing classname which is inside for loop

    {% for pbyid in productbyid %}

<div class="card card_body m-2 p-0 container" id='{{pbyid.id}}'>
<div>
  <div>
  <a href="/viewpage/{{pbyid.id}}"><div class='imagestyle' ><img class="card-img-top " src="{{pbyid.image}}"width="500" height="200" alt="Card image cap "></div></a>
  <span class="top-left">{{pbyid.discountpercentage}}% off</span>
  </div>
  <div class="card-body">
    <h5 class="card-title cardtitle">{{pbyid.title}}</h5>
    <div><p class="carddesccrip">{{pbyid.desc}} </p></div>
    <div class='pricce_card'>
    <span class='price'> <b>M.R.P</b> <strike class='carddesc'>RS {{pbyid.discountPrice}}</strike></span>
    <span class='final_price'><b>RS. {{pbyid.finalprice}}</b></span>
    
</div>
  </div>
  <div class="card-body">
  {% comment %} /viewpage/{{pbyid.id}} {% endcomment %}
     <p href="" id='' class="btn btn-lg btn-block addbtn caddtocart" onclick="myFunction({{pbyid.id}})" > Add to cart 
     <i class="fa fa-plus float-right align-center p-2 plusbtn" aria-hidden="true"></i></p> 
  </div>
  </div>



  </div>

 {% endfor %}

js how can i change html of btn from class , when i try it doesn't wok with classname but it work with id , but for id is specific so we have to use classname but i'm not exactly getting how to solve can anyone have idea to solve it

function myFunction(id) {
var x = document.getElementsByClassName("caddtocart");

x.innerHTML = "added";
console.log(id);

}
 <-- another method -->
var x = document.getElementsByClassName("caddtocart");


    x.forEach(myFunction(id))
    {
    document.getElementsByClassName("caddtocart").innerHTML = "Paragraph changed!";
    console.log(id);
    }
       

 </script>
SuNdar A.D
  • 11
  • 4
  • Does this answer your question? [JS: iterating over result of getElementsByClassName using Array.forEach](https://stackoverflow.com/questions/3871547/js-iterating-over-result-of-getelementsbyclassname-using-array-foreach) – Sirwill98 Jan 18 '21 at 16:28
  • i try but not solving problems see above what i did – SuNdar A.D Jan 18 '21 at 16:42

1 Answers1

0

Try the below code:

function myFunction(id) {
    var els = document.getElementsByClassName("caddtocart");

    Array.prototype.forEach.call(els, function(el) {
        elm.innerHTML = "Paragraph changed!";
        console.log(el.id);
    });
}

Or first check for id:

function myFunction(id) {
    if(id) {
        var elm = document.getElementById(id);
        elm.innerHTML = "Paragraph changed!";
    } else {
        var els = document.getElementsByClassName("caddtocart");

        Array.prototype.forEach.call(els, function(el) {
            elm.innerHTML = "Paragraph changed!";
            console.log(el.id);
        });
    }
}
NKSM
  • 5,422
  • 4
  • 25
  • 38