You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取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 attributesChangeCallback but the correct Custom Elements API method is attributeChangedCallback (note the singular "attribute" and proper spelling).
  • Missing callback parameters: The attributeChangedCallback requires three parameters: name, oldValue, and newValue.
  • Scope problem with addTxt: Your addTxt function is defined inside connectedCallback, so it's not accessible as an instance method via this.addTxt().
  • No initial value handling: Your element doesn't load the initial value attribute 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

  1. Proper attribute observation: The corrected attributeChangedCallback triggers whenever the value attribute changes, and updates the UI via the addTxt class method.
  2. Initial value loading: When the element first connects to the DOM, it grabs the initial value attribute and renders it immediately.
  3. 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 calling setAttribute.
  4. Improved element scope: By storing internal DOM elements as instance properties, we avoid relying on global document.getElementById calls, which can cause conflicts if multiple <custom-select> elements exist on the page.

内容的提问来源于stack exchange,提问作者GDTyka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 15:47:37