Как переименовать текст h1 с помощью javascript (на wordpress) - PullRequest
0 голосов
/ 08 мая 2020

Я хотел бы переименовать текст h1 в заголовке для любой отдельной страницы, возможно ли это с помощью скрипта?

Строка заголовка:

enter image description here

Ответы [ 4 ]

1 голос
/ 08 мая 2020

Вот так

Я оборачиваю событие загрузки страницы, а затем использую ближайший известный селектор

Если у вас есть class = "titoloheader", код даже проще, чем использование

div[data-row=middle] h1

Если вы хотите изменить только на страницах с /articoli/, вы можете проверить путь:

 const url = new URL(location.href); 
 if (url.pathname.split("/").indexOf("articoli") !=-1) {
   document.querySelector("h1.titoloheader").innerText = "Hello"
  }  
})

Если вы хотите изменить на page-id-X, вы можно так:

ваниль JS

const pageTitles = {
  "41": "Hello",
  "44": "Goodbye",
  "47": "Ciao",
  "3": "Arriverderci",
  "313": "Hey",
  "316": " Bye",
  "318": " This is silly",
  "50": "The end"
};

const changeHeader = () => {
  let id = [...document.body.classList] // all the classes of the body tag
    .filter(classStr => classStr.startsWith("page-id")); // find the one that starts with page-id
  if (id.length)[, , id] = id[0].split("-") // if found (an array) grab the last part after last -
  if (id && Object.keys(pageTitles).includes(id)) { // do we find that ID in the list
    document.querySelector("h1.titoloheader").innerText = pageTitles[id]; // change the header
  }
};

window.addEventListener("load", changeHeader); // when the page loads
<body class="home page-template-default page page-id-47 logged-in admin-bar no-customize-support ct-loading" data-link="type-1" data-forms="classic">

  <div data-row="middle" data-columns="1">
    <div class="ct-container">
      <div data-column="middle">
        <div data-items="">
          <div class="ct-header-text " data-id="text">
            <div class="entry-content">
              <h1 class="titoloheader">Benvenuti</h1>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

jQuery

const pageTitles = {
  "41": "Hello",
  "44": "Goodbye",
  "47": "Ciao",
  "3": "Arriverderci",
  "313": "Hey",
  "316": " Bye",
  "318": " This is silly",
  "50": "The end"
};

const changeHeader = () => {
  let id = [...document.body.classList] // all the classes of the body tag
    .filter(classStr => classStr.startsWith("page-id")); // find the one that starts with page-id
  if (id.length)[, , id] = id[0].split("-") // if found (an array) grab the last part after last -
  if (id && Object.keys(pageTitles).includes(id)) { // do we find that ID in the list
    $("h1.titoloheader").text(pageTitles[id]); // change the header
  }
};

$(document).ready(changeHeader);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <body class="home page-template-default page page-id-47 logged-in admin-bar no-customize-support ct-loading" data-link="type-1" data-forms="classic">
<div data-row="middle" data-columns="1">
  <div class="ct-container">
    <div data-column="middle">
      <div data-items="">
        <div class="ct-header-text " data-id="text">
          <div class="entry-content">
            <h1 class="titoloheader">Benvenuti</h1>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
0 голосов
/ 08 мая 2020

Чтобы изменить текст элемента h1 в вашем примере при загрузке страницы, вы можете использовать:

window.addEventListener('load', event => {
  const h1Element = document.querySelector("#main-container .entry-content h1");
  h1Element.innerText = 'New H1 Text';
});

Если вы не вносите изменения в H1 в обратного вызова события загрузки окна, целевой элемент, скорее всего, не будет доступен в DOM, когда вы попытаетесь получить к нему доступ с помощью document.querySelector.

0 голосов
/ 08 мая 2020

Вот простой пример из школ W3

<!DOCTYPE HTML>
<html>
<body>

<h1 id="myHeader">Hello World!</h1>
<button onclick="displayResult()">Change text</button>

<script>
function displayResult() {
  document.getElementById("myHeader").innerHTML = "Have a nice day!";
}
</script>

</body>
</html>

Если вы заметили, они добавляют уникальный идентификатор к тегу h1. Таким образом, вы можете получить доступ к тегу напрямую.

https://www.w3schools.com/tags/att_id.asp

0 голосов
/ 08 мая 2020

jQuery:

$('#main-container div[data-row="middle"] .entry-content h1').html('Your New Title');

Ванила JS:

var el = document.querySelector("#main-container div[data-row="middle"] .entry-content h1");
el.innerHTML= "Your New Title";
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...