Home > Net >  how to sending Dynamic Id sending getElementById to js function
how to sending Dynamic Id sending getElementById to js function

Time:12-21

                                        <div id="product-zoom-gallery" >
                                            @foreach (var item in Model.Images)
                                            {
                                                <a onclick="myFunction('@item')"  href="#" @*onclick="changeImg('/@item');"*@
                                               data-image="/@item"
                                               data-zoom-image="/@item">
                                                    <img id="myImg @item"  src="/@item"
                                                     >
                                                </a>
                                            }


                                        </div>

I want to send a dynamic ID to myFunction(item), where "item" is my dynamic ID and I want to send that like this to getElementById method:

        function myFunction(item){
            var string = `"myImg ${item}"`
            alert(string);
            var modal = document.getElementById("myModal");

            var img = document.getElementById(`"${string}"`);
            var modalImg = document.getElementById("img01");
            var captionText = document.getElementById("caption");
            img.onclick = function () {
                modal.style.display = "block";
                modalImg.src = this.src;
                captionText.innerHTML = this.alt;
            }

            // Get the <span> element that closes the modal
            var span = document.getElementsByClassName("close")[0];

            // When the user clicks on <span> (x), close the modal
            span.onclick = function () {
                modal.style.display = "none";
            }
        }

But the var img does not work for me. I would expect from var img = document.getElementById("${string}");, to find my img tag.

CodePudding user response:

  1. Whitespaces are not supported in the id attribute. In general, you should stick to alphanumeric ASCII-friendly characters (and not start with a number). Besides letters and numbers, you can also use _ or - as separators.
  2. There's some redundant quotations (") in your template literals (between the backticks ``), since the backticks already convert its content into a string automatically.

So your could would become:

<img id="myImg-item">
function myFunction(id){
    var string = `myImg-${id}`
    alert(string);
    
    var modal = document.getElementById("myModal");
    var img = document.getElementById(string);

Now if you call your function: myFunction('item'), it will assemble the ID "myImg-item" and the getElementById lookup should succeed.

For more information, please read up on the id attribute on the MDN docs

  • Related