- 我是 js 新手。
- 你能告诉我为什么我得到 sports-title 和 third 的空值吗?
- 因为我们有一个包含内容的 div。 运动标题---->{"0":{}} 第三个---->{}
- 在下面提供我的代码。
findStringInsideDiv() {
/*
var str = document.getElementsByClassName("sports-title").innerHTML;
*/
var sportsTitle = document.getElementsByClassName("sports-title");
var third = sportsTitle[0];
var thirdHTML = third.innerHTML
//str = str.split(" ")[4];
console.log("sports-title---->" + JSON.stringify(sportsTitle));
console.log("third---->" + JSON.stringify(third));
console.log("thirdHTML---->" + JSON.stringify(thirdHTML));
if ( thirdHTML === " basketball football swimming " ) {
console.log("matching basketball---->");
var menu = document.querySelector('.sports');
menu.classList.add('sports-with-basketball');
// how to add this class name directly to the first div after body.
// but we are not rendering that div in accordion
//is it possible
}
else{
console.log("not matching");
}
}
最佳答案
当您使用任何 GetElement 选择器调用文档对象模型 (DOM) 中的对象时,它会返回一个可被视为该 HTML 元素的对象。该对象不仅仅包括 HTML 元素中包含的文本。为了访问该元素的文本,您需要使用 .textContent 属性。
此外,一个 HTML 类可能被分配给多个元素,因此 GetElementsByClassName 返回一个数组,因此您必须执行以下操作,例如:
console.log("sports-title---->" + JSON.stringify(sportsTitle[0].textContent));
您可以在 W3School 网站上找到对 DOM 的简要介绍。 https://www.w3schools.com/js/js_htmldom.asp如果您继续阅读,它会概述 DOM 的不同方面,包括元素。
关于javascript - 我得到体育冠军和第三名的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43749024/