Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the first header tag in the document (<h2>,<h3>..<h6>) to <h1>

If <h1> doesn't exist, find the first header tag in the document (one of either <h2> through <h6>), and if the tags text equals the title text, change the element to <h1 class="heading1">.

This works as far as I can tell, but there has to be a more efficient way to write it.

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>";
    });
}
like image 285
Andy Dudley Avatar asked Dec 09 '22 19:12

Andy Dudley


1 Answers

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);
    }
  }
});
like image 162
ValeriiVasin Avatar answered Dec 11 '22 09:12

ValeriiVasin