Search code examples
javascripthtmlcustom-element

JS Custom Elements, how I can get attribute value


I'm just learning, and so I decided to repeat the tags that already exist, so

I have custom element custom-select, he must do same thing as select, but i need to get value of attribute value

this is my code of custom element

class CustomSelect extends HTMLElement{

            static get observedAttributes(){
                return ["value"]
            }

            attributesChangeCallback(name,val){
                console.log("1234")
                if(name === "value"){
                    this.addTxt(val)
                }
            }

            connectedCallback(){



                this.innerHTML = `
                <div class = "first" id = "divId"></div>
                <div id = "spisoc">

                </div>
                `

                let elem = document.getElementById('divId')
                let elem2 = document.getElementById('spisoc')
                elem.onclick = function(){
                    elem2.classList.add("spisocDesing")
                }
                function addTxt(val){
                    elem2.innerHTML += val
                }

            }
            
        }
        customElements.define('custom-select',CustomSelect)

and this is html inside body

<body>
    <custom-select id = "elem" value = "1234">

    </custom-select>
    <script>
    </script>
</body>
</html>

Solution

  • you can follow below script for custom elements

    <some-element cutom-elem /> <other-element custom-elem />
    <script> 
      var customs = document.querySelectorAll( "*[custom-elem]" )
    </script>
    <style>
        *[custom-elem] { display: block ; }
    </style>