Skip to content
Advertisement

How to get the text of H1 tag and copy it to another part of the code with Javascript?

I am in the process of adding “See more” sections to the bottom of some of my web pages. My plan to is to have something like this:

<h1 id="test">Unique title</h1>

<h2>See more</h2>
<ul>
<li><a class="link" href="/people/YYYY/category1/">More1</a></li>
<li><a class="link" href="/people/YYYY/category2/">More2</a></li>
<li><a class="link" href="/people/YYYY/category3/">More3</a></li>
<li><a class="link" href="/people/YYYY/category4/">More4</a></li>
<ul>

<script>
let text = document.getElementById("link").innerHTML; 
document.getElementByClass("link").innerHTML = text.replace("YYYY", "test");
</script>

I have tried the above script but to no avail.

I have many hundreds of these to do so what I’m looking to do is use Javascript to copy the text in the H1 tag and replace ‘YYYY’ in the url with that text within the same page.

I have very limited knowledge of Javascript, I tend to only use WS3 snippets, but I’m struggling to find something for what I need.

Please note: there is more code between the H1 and H2 tags, I just haven’t included it. Also, the urls in the ul are examples only.

Advertisement

Answer

Here’s an answer to what you are asking, but it is probably not the right way to do what you are trying to do. You probably want to use some sort of back-end code, or a build system.

To get the text content of a tag, you should first add an id attribute to it, to make it easy to target with Javascript:

<h2 id="foo">Blah Blah</h2>

Then you can easily get a reference that tag with Javascript, and then use the innerText property to get the text.

var text = document.getElementById('foo').innerText

To replace the text of several href attributes is more tricky. You can first get a reference to them, I suggest using an id attribute on the <ul> tag to make this easier:

<ul id="special-links">

Then you can use querySelectorAll to find the tags:

var aTags = document.querySelectorAll('#special-links a')

Then loop through those using forEach. For each iteration of the loop, use getAttribute to get the href attribute, then use replace to replace the YYYY portion with the text value we got previously, then use setAttribute to set that new string as the new href.

aTags.forEach((tag) => {
    let href = tag.getAttribute('href')
    let newHref = href.replace('YYYY', text)
    tag.setAttribute('href', newHref)
})
Advertisement