[英]How to get the innerHTML/innerText from a related node of a clicked element?
[英]How do get a character count from innerText or InnerHTML using dojo?
我必須在我的應用程序中使用Dojo
,並且試圖在HTML
元素中獲取總數,但我不斷收到錯誤消息。
這是我的代碼:
var attributeIcons = dojo.query(".attribute-icon"); if (attributeIcons.innerText.length = 4) { console.log(attributeIcons); }
我也嘗試使用這種方法:
var attributeIcons = document.getElementsByClassName("attribute-icon").innerHTML.length; console.log(attributeIcons);
每種方法都給我相同的錯誤:
Uncaught TypeError: Cannot read property 'length' of undefined
document.getElementsByClassName("attribute-icon")
或dojo.query(".attribute-icon")
返回數組,您需要像這樣遍歷該數組,
var attributeIcons = document.getElementsByClassName("attribute-icon");
Array.prototype.forEach.call(attributeIcons, function(el) {
console.log(el.innerHTML.length);
});
dojo.query()和document.getElementsByClassName()都返回類似數組的對象。 這意味着您無法在節點數組上調用.innerHTML(您將得到未定義),隨后您也無法調用.length。
查看以下兩個參考: https : //dojotoolkit.org/reference-guide/1.7/dojo/query.html,https : //developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
嘗試運行以下命令以查看您的陣列。
var attributeIcons = dojo.query(".attribute-icon"); console.log(attributeIcons) // or var attributeIcons = document.getElementsByClassName("attribute-icon"); console.log(attributeIcons)
您可以選擇一個數組項,然后在其上運行.innerHTML.length,而不是在整個數組上運行。
var attributeIcons = dojo.query(".attribute-icon"); console.log(attributeIcons[0].innerHTML.length) // or var attributeIcons = document.getElementsByClassName("attribute-icon"); console.log(attributeIcons[0].innerHTML.length)
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.