javascript - 将文档中的第一个标题标签 (<h2>,<h3>..<h6>) 更改为 <h1>

标签 javascript jquery

如果<h1>不存在,找到文档中的第一个标题标签(<h2><h6> 之一),如果标签文本等于标题文本,将元素更改为 <h1 class="heading1"> .

据我所知,这是可行的,但必须有一种更有效的方式来编写它。

var titleText = $('title').html()
var hOne = $('h1:eq(0)');
var hTwo = $('h2:eq(0)');
var hThree = $('h3:eq(0)');
var hFour = $('h4:eq(0)');
if (hOne.html() == titleText)
{
    return;
}
else if (hTwo.html() == titleText)
{
    var hTwoText = hTwo.html();
    hTwo.replaceWith(function () {
        return '<h1 class="heading1">' + hTwoText + "</h1>";
    });
}
else if (hThree.html() == titleText)
{
    var hThreeText = hThree.html();
    hThree.replaceWith(function () {
        return '<h1 class="heading1">' + hThreeText + "</h1>";
    });
}

else if (hFour.html() == titleText)
{
    var hFourText = hFour.html();
    hFour.replaceWith(function () {
        return '<h1 class="heading1">' + hFourText + "</h1>";
    });
}

最佳答案

Try it

$(function () {
  var title,
      headerToReplace,
      replacer;

  if ( $('h1').length === 0 ) {
    title = document.title;
    headerToReplace = $(':header').filter(function () {
      return $(this).text() === title;
    });

    if (headerToReplace.length) {
      replacer = $('<h1 />', { 'class': 'heading1', text: 'title' });
      headerToReplace.first().replaceWith(replacer);
    }
  }
});

关于javascript - 将文档中的第一个标题标签 (<h2>,<h3>..<h6>) 更改为 <h1>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866300/

相关文章:

jquery - 克隆 <select> 并添加删除按钮

javascript - 使用translatePartialLoader时如何解决 Angular 翻译FOUC问题?

javascript - 从 JavaScript 数组中删除嵌套的空值

javascript - jQuery Ajax 在 cordova iOS 应用程序上发送之前触发成功

javascript - 为什么我的 Owl Carousel 在我的第一组中不起作用?请问我的eero在哪里?

jquery - 为什么包含 Snook 的简单 jQuery 幻灯片的 Bootstrap 行的高度为 0?

javascript - 将 onclick 添加到元素,但保留当前 onclick 事件

javascript - react native : How to get <TextInput/> to start from right to left?

javascript - 等待 api 调用的异步 ajax 的完整响应

javascript - 删除前触发动画结束