0

If I have a title with multiple consecutive spaces, document.title returns a string with a single space for each such space combo.

Example:
<title>[ ]</title> - HTML
"[ ]" - document.title

See also image below.

Question - how to get the raw string as it's defined in the HTML document? This caused a bug in one of my scraping scripts where a title should match some other element.

screenshot

7
  • document.getElementsByTagName('title')[0].innerHTML? I don't know why this works, but it does... Commented Dec 10, 2020 at 19:35
  • @nthnchu document.getElementsByTagName('title')[0].innerHTML is just awful code. And don't use .innerHTML when the string doesn't contain any HTML. Commented Dec 10, 2020 at 19:36
  • @nthnchu just found it myself here, thanks: stackoverflow.com/a/43606154/2604492 Commented Dec 10, 2020 at 19:37
  • @Paul No. See my comment to your answer. Commented Dec 10, 2020 at 19:37
  • @SᴀᴍOnᴇᴌᴀ how is it a duplicate if the top answer suggests the code that caused my problem? Commented Jun 8, 2021 at 16:12

1 Answer 1

1

Looks like I found the answer myself, using the following works:
document.getElementsByTagName('title')[0].textContent

According to the comment of Scott Marcus (this answer), it's better to use:
document.querySelector("title").textContent

Sign up to request clarification or add additional context in comments.

13 Comments

No. Use document.querySelector("title").textContent Your answer relies on just horrible code.
I agree that document.querySelector is the more efficient way, but labeling the other as "horrible/awful code" is a bit dramatic. It's fine; just maybe not the "best."
@Teemu It's not inherently good either. And, finding everything and putting it all in a collection, only to grab the first one and then throw away the collection is a waste of resources in all use cases.
It's unnecessary to insult the code. It works. it does the job. If the purpose of the code is simple and/or the performance doesn't matter, then it really doesn't matter if the other code is used. I think most people would recommend NOT to use that code simply because we should train ourselves to always choose the most efficient code. But like I said before: you're being dramatic calling it "horrible" or "awful."
@daddygames I'm not violating any code of conduct because I'm not insulting anyone. I'm point out that code is bad - - that's not a bad thing. In fact, that's exactly the kind of thing we are supposed to do here. The code I'm talking about is potentially dangerous to use. It warrants a severe response. Right up there with eval().
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.