1
<h2 class="post-title"> ==$0
    "Title of the post" 
    <span class="post-date">1 jan 2000</span>  
    <span class="post-tag">Tag</span>
</h2>

What I want is only the post title "Title of the post"

Title = document.getElementsByClassName("post-title");
Title[0].innerText

What I'm getting is "Title of the post 1 jan 2000 Tag"

Rayly Esta
  • 33
  • 8
  • is the part ` ==$0` a typo or is that really in the `

    ` element?

    – caramba Nov 02 '20 at 19:34
  • @caramba It's what you see in Chrome devtools when you select an element. It tells you that you can use the variable $0 in the console to refer to that element. – Barmar Nov 02 '20 at 19:36

1 Answers1

1

you could use a regex

var element = document.querySelector('.post-title');
var regexMatches = element.textContent.match(/"(.*)"/);

console.log('with quotes: ' + regexMatches[0]);
console.log('without quotes: ' + regexMatches[1]);
<h2 class="post-title"> ==$0
    "Title of the post" 
    <span class="post-date">1 jan 2000</span>  
    <span class="post-tag">Tag</span>
</h2>
caramba
  • 21,963
  • 19
  • 86
  • 127
  • The quotes probably aren't in the actual text. That's just the way DevTools shows text nodes. – Barmar Nov 02 '20 at 19:38
  • @Barmar thanks again, I've updated the answer – caramba Nov 02 '20 at 19:41
  • You still have the quotes and `==$0` in the HTML. Those aren't in the HTML, they're just in the Elements panel of DevTools. – Barmar Nov 02 '20 at 19:45
  • This will work for your HTML, but I don't think it will work for the real thing. – Barmar Nov 02 '20 at 19:46
  • @Barmar thank for all the inputs! I've never seen `==$0` in my dev tools. Either way the regex works with and without that part. Why are you so sure that you can say "it will not work on the real thing"? I really wonder, I mean, the question did not provide more information or did I overlook something? – caramba Nov 02 '20 at 19:50
  • Aah now I see, you @Barmar probably mean the "quotes" were just here for illustration purposes, that would make sense, and then all the effort was for nothing :facepalm – caramba Nov 02 '20 at 19:53
  • Because it looks like the OP copied the view of the elements from the DOM inspector, and I know that it adds quotes around text nodes, even though the quotes are not actually in the HTML. – Barmar Nov 02 '20 at 19:53
  • The `= $0` part is the clue. If you click on an element in DevTools, you'll see that in the inspector. – Barmar Nov 02 '20 at 19:54
  • @Barmar thank you! Really I look up to guys like you from which I can learn a lot! I will leave the answer for a while. Maybe I delete it later. Let's see what happens – caramba Nov 02 '20 at 19:55