简体   繁体   English

document.getElementById并使用类名

[英]document.getElementById and using classname

I have the following in HTML code: HTML代码中包含以下内容:

<div id="story" class="componentBox">
  <h1 class="articleTitle">Parlamentarzyści nie stracą emerytur</h1>
  <div class="artDetails">19 kwietnia 2016 | Kraj |  Wiktor Ferfecki</div>
  <div class="storyContent">

To retrieve the contents of articleTitle I use: 要检索articleTitle的内容,我使用:

document.getElementById("story").getElementsByTagName("div")[0].innertext

And to retrieve the contents of artDetails 并检索artDetails的内容

document.getElementById("story").getElementsByTagName("div")[0].innertext

I think that it would be better to make use of the titles ie articleTitle and artDetails . 我认为最好使用标题,即articleTitleartDetails I have no clues how to do it whatsoever. 我不知道该怎么做。 I've tried document.getElementById("story").getElementByClassName("articleTitle")[0].innertext but it throws and error. 我尝试了document.getElementById("story").getElementByClassName("articleTitle")[0].innertext但它抛出并出错。

You can use querySelector() to select an element and use textContent property on HTMLNode to get the text content of the element. 您可以使用querySelector()选择一个元素,并使用HTMLNode上的textContent属性获取该元素的文本内容。

var title = document.querySelector('#story .articleTitle').textContent;

var details = document.querySelector('#story .artDetails').textContent;

 var title = document.querySelector('#story .articleTitle').textContent; var details = document.querySelector('#story .artDetails').textContent; document.body.innerHTML = 'Title: ' + title + '<br /> Details: ' + details; 
 <div id="story" class="componentBox"> <h1 class="articleTitle">Parlamentarzyści nie stracą emerytur</h1> <div class="artDetails">19 kwietnia 2016 | Kraj | Wiktor Ferfecki</div> <div class="storyContent"> 

While you can use the document.GetElementsByClassName() function to target specific classes, if you want to target a specific element, you may be better off using the document.querySelector() function as seen below : 虽然可以使用document.GetElementsByClassName()函数来定位特定的类,但是如果要定位特定的元素,则最好使用document.querySelector()函数,如下所示:

// Get the title (i.e. the "articleTitle" class below an element with ID "story"
var title = document.querySelector('#story .articleTitle').textContent;
// Do the same for the details...
var details = document.querySelector('#story .artDetails').textContent;

You can see a working example here and demonstrated below : 您可以在此处看到一个工作示例,并在下面进行了演示:

在此处输入图片说明

I'd highly recommend looking into jQuery . 强烈建议您研究jQuery It will help you do more with less. 这将帮助您事半功倍。 So instead of doing this: 所以不要这样做:

document.getElementById("story").getElementsByTagName("div")[0].innertext

You could write this: 您可以这样写:

$('#story .artDetails')[0].innertext

And you would still accomplish the same thing. 而且您仍然会完成同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM