如何在javascript中获得HTML网页的标题?

652 阅读1分钟

在本教程中,学习如何用javascript获得当前网页的HTML标题。

还有,如何在javascript中用数值更新页面标题。

在Html页面上,Title 标签包含一个完整的网页的文本内容。</code> tag in HTML contains text content.</p><p>Here is a title example in HTML</p><h2>how to get the Current page title in javascript?</h2><p>There are several ways to get the current page title in javascript.</p><p>First, an easy way is using <code>document.title</code>.</p><div><pre><code>console.log(document.title) </code></pre></div><p>Second, using dom <code>getElementsByTagName</code> API <code>getElementsByTagName('title')</code> returns array of elements, get the first element.</p><p><code>textContent</code> property on HTML element returns title of an page.</p><p>you can also use <code>innerHTML</code> to get the title. <code>textContent</code> is recommeded one to get title.</p><div><pre><code>var titleElement = document.getElementsByTagName("title")[0]; console.log(titleElement) //<title> Hello World titleconsole.log(titleElement.textContent) //Hello World title console.log(titleElement.innerHTML) //Hello World title

  • 使用jquery选择器的语法获得标题。

首先,使用HTML元素选择器语法选择一个文档。用title标签过滤DOM元素,并返回title HTML元素 最后,调用text()方法来获取文本内容。

var titleText = $(html).filter('title').text();
console.log(titleText) //Hello World title

或者你可以尝试

如何使用javascript和jquery来改变网页的标题

有多种方法,我们可以改变标题。

  • 使用文档对象,用新的值改变标题属性
document.title = 'New HTML title value';
  • 另一种是使用getElementsByTagName

首先使用getElementsByTagName获得一个元素,然后直接改变标题。

document.getElementsByTagName('title')[0]='New html title value content';
  • jquery改变标题 选择一个html元素,找到标题并使用text() 方法更新标题。
$(html).find('title').text('new html title value using jquery');