我获得了体育冠军和第三名的空值 [英] I am getting empty values for sports-title and third

查看:77
本文介绍了我获得了体育冠军和第三名的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • 我是js的新手。

  • 你能告诉我为什么我会为体育冠军和第三名获得空值。 $ b
  • ,因为我们有一个包含内容的div。
    sports-title ----> {0:{}}
    third ----> {}

  • 提供下面的代码。 li>
  • i am new to js.
  • can you tell me why I am getting empty values for sports-title and third.
  • since we have one div with content in it. sports-title---->{"0":{}} third---->{}
  • providing my code below.
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属性。

When you call an object in the Document Object Model (DOM) using any of the GetElement selectors, it returns an object that can be considered that HTML element. This object includes much more than just the text included in the HTML element. In order to access the text of that element, you want to use the .textContent property.

另外,一个HTML类可能被分配给几个元素,因此GetElementsByClassName返回一个数组,因此您必须执行以下操作,例如:

In addition, an HTML class can potentially be assigned to several elements and therefore GetElementsByClassName returns an array so you would have to do the following, for example:

console.log("sports-title---->" + JSON.stringify(sportsTitle[0].textContent));

您可以在W3Schools网站上找到关于DOM的简要介绍。 https://www.w3schools.com/js/js_htmldom.asp 如果你关注沿着它概述了DOM的各个方面,包括元素。

You can find a brief introduction to the DOM on the W3Schools Website. https://www.w3schools.com/js/js_htmldom.asp If you follow along it gives an overview of different aspects of the DOM including elements.

这篇关于我获得了体育冠军和第三名的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆