如何获取JavaScript自定义元素(Custom Elements)的value属性值?
Fixing Your
custom-select Element to Access the value Attribute Hey there! Let's get your custom <custom-select> element working properly so you can access and use its value attribute. I spotted a couple of key issues in your code that are preventing it from behaving as expected—let's walk through them step by step.
Key Issues in Your Current Code
- Incorrect callback method name: You wrote
attributesChangeCallbackbut the correct Custom Elements API method isattributeChangedCallback(note the singular "attribute" and proper spelling). - Missing callback parameters: The
attributeChangedCallbackrequires three parameters:name,oldValue, andnewValue. - Scope problem with
addTxt: YouraddTxtfunction is defined insideconnectedCallback, so it's not accessible as an instance method viathis.addTxt(). - No initial value handling: Your element doesn't load the initial
valueattribute when it first connects to the DOM.
Modified Working Code
Updated Custom Element JavaScript
class CustomSelect extends HTMLElement { static get observedAttributes() { return ["value"]; } // Corrected callback with proper parameters attributeChangedCallback(name, oldValue, newValue) { console.log(`Attribute ${name} changed from ${oldValue} to ${newValue}`); if (name === "value" && newValue !== oldValue) { this.addTxt(newValue); } } connectedCallback() { this.innerHTML = ` <div class="first" id="divId"></div> <div id="spisoc"></div> `; // Store elements as instance properties to avoid global DOM lookups this.elem = this.querySelector('#divId'); this.elem2 = this.querySelector('#spisoc'); this.elem.onclick = () => { this.elem2.classList.add("spisocDesing"); }; // Load initial value when the element connects to the DOM const initialValue = this.getAttribute("value"); if (initialValue) { this.addTxt(initialValue); } } // Convert addTxt to a class method for cross-callback access addTxt(val) { this.elem2.innerHTML += val; } // Optional: Add a getter for native-like value access get value() { return this.getAttribute("value"); } // Optional: Add a setter to update attribute and UI seamlessly set value(newVal) { this.setAttribute("value", newVal); } } customElements.define('custom-select', CustomSelect);
Updated HTML
<body> <custom-select id="elem" value="1234"></custom-select> <script> // Example: Access and update the custom element's value const customSelect = document.getElementById('elem'); // Get the current value console.log("Initial value:", customSelect.value); // Example: Update the value after 2 seconds setTimeout(() => { customSelect.value = "5678"; console.log("Updated value:", customSelect.value); }, 2000); </script> </body>
How It Works Now
- Proper attribute observation: The corrected
attributeChangedCallbacktriggers whenever thevalueattribute changes, and updates the UI via theaddTxtclass method. - Initial value loading: When the element first connects to the DOM, it grabs the initial
valueattribute and renders it immediately. - Native-like value access: The
get value()getter lets you access the value just like a native<select>element (customSelect.value), and the setter lets you update it without manually callingsetAttribute. - Improved element scope: By storing internal DOM elements as instance properties, we avoid relying on global
document.getElementByIdcalls, which can cause conflicts if multiple<custom-select>elements exist on the page.
内容的提问来源于stack exchange,提问作者GDTyka
相关产品推荐
相关产品推荐

