英文:
Get element by data-i18n-key
问题
以下是已经翻译好的内容:
我试图获取由外部应用程序添加的元素。我能够获取这个特定的元素的唯一方法是通过data-i18n-key属性,我以为我可以像获取任何数据属性一样获取它,就像这样。
这段代码:
```javascript
const buttons = document.querySelectorAll('[data-i18n-key="sdk.seamless_product_reward.paid_items_required"]');
console.log(buttons.length);
然而,这并没有返回任何内容。有没有办法可以做到这一点?
<details>
<summary>英文:</summary>
I'm trying to get an element which is added by an external application. The only way I can get this specific element is by the data-i18n-key attribute which I thought I can grab like any data attribute so something like this.
The code:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const buttons = document.querySelectorAll('[data-i18n-key="sdk.seamless_product_reward.paid_items_required"]');
console.log(buttons.length);
<!-- language: lang-html -->
<span class="lion-reward-item__redeem-button-text lion-loyalty-page-reward-item__redeem-button-text" data-i18n-key="sdk.seamless_product_reward.paid_items_required">Paid items required</span>
<!-- end snippet -->
However, this doesn't return anything. Any ideas how to do this?
</details>
# 答案1
**得分**: 1
当然,Barmer是绝对正确的。你的代码有效。问题在于你的JS在DOM完成加载之前就被初始化了。将你的JS放在闭合的`</body>`标签之上。
<details>
<summary>英文:</summary>
Of course, Barmer is absolutely right. Your code works. The problem will be that your JS is initialised before the DOM has finished loading. Pack your JS above the closing body tag.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论