简体   繁体   中英

How to repeat early text in the same HTML file using Javascript

I'm looking to create a new page for my articles on my site that replicates the contents of my <h1> tag later in the page.

I wanted to include a small bit of code (I imagined Javascript, but something else will do) - to dyanmically add the Title <h1> of my article in the bottom so it will look something like this:


<h1> This is the title of the article </h1>

 and then at the end of the page:

  Related Articles:

   <p> If you enjoyed reading 
         <script>... populatate "This is the title of the article"</script> 
  then why not explore the following similar articles? </p>

I've looked into it and can't seem to see how to do this more than replicating the <title> tag. It's probably really simple but does anyone know how to do this?

HTML

<h1 id="something"> title </h1>
<h1 id="repeated_title"></h1>

JQUERY

$("#repeated_title").text($("#something").text());

If you have code like this:

If you enjoyed reading <span id="populate"></span>

You can write a jQuery snippet like:

$(function(){
    $('#populate').text($('h1').text());
});

It would probably be a better idea to duplicate the data when the HTML is generated / written instead of at runtime, but in case that's not possible, wrap the place where you want to copy the text to into an element that you can refer to, for example by id:

<span id="title_copy"></span>

Then, figure out a way to refer to the header you want to copy the text from, for example by ID again:

<h1 id="main_title">This is the title of the article</h1>

Then you can use JS to copy the contents of "main_title" to "title_copy":

document.getElementById('title_copy').innerHTML = document.getElementById('main_title').innerHTML;

In pure Javascript this is how you would do it (Look Ma, No jQuery)

<h1 id="something"> title </h1>
If you enjoyed reading <span id="populate"></span>

Javascript

<script>
    document.getElementById("populate").innerHTML = document.getElementById("something").innerHTML;
</script>

Probably best to do it server side though.

PS You don't have to place the <script> tag there. Anywhere in the document will do, and its mostly done in the <head>

there is many ways to do this, and javascript is not the best one, as you should do this server side.

<h1 id='title'> This is the title of the article </h1>

and then at the end of the page:

Related Articles:

<p> If you enjoyed reading <span id="title2"></span> then why not explore the following similar articles? [/p]
<script>$("#title2").text(#("#title").text);</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM