menteith menteith - 7 months ago 24
HTML Question

document.getElementById and using classname

I have the following in HTML code:

<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:

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


And to retrieve the contents of
artDetails


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


I think that it would be better to make use of the titles i.e.
articleTitle
and
artDetails
. I have no clues how to do it whatsoever. I've tried
document.getElementById("story").getElementByClassName("articleTitle")[0].innertext
but it throws and error.

Answer

You can use querySelector() to select an element and use textContent property on HTMLNode to get the text content of the element.

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">