Dynamically create html header tag using javascript

I have many pages on the im development site in which each page has its own title tag. In many cases, the headers have constant text, for example:

Home | Section 1 | Page 1
Home | Section 1 | Page 2
Home | Section 1 | Page 3, etc ...

Inserting these headings leads to more difficult changes later, not to mention the difficulties of remembering to add them. I am looking to find a way to dynamically create the title of each page using javascript based on the location of the page in the folder structure of the site.

I am currently using a script that does something like this for breadcrumbs, but I'm not sure how to link to the same script, or create similar ones for page headers. The wand script is here: http://trcreative.us/dev/jmsracing/js/breadcrumbs.js

and for the most part does exactly what I need for the headers, minus the links for each element of the palette. (I do not want this to do this explicitly for the name).

See breadcrumbs here: http://trcreative.us/dev/jmsracing/races/pigman-long-and-olympic/

Any help would be greatly appreciated. thank you

+4
source share
4 answers

Assuming your URL matches the following home/section/page.html , you can use this function at the top of any page and set a title based on the URL if that is what you mean.

 function setTitle(extra) { document.title = location.pathname.split('/').map(function(v) { return v.replace(/\.(html|php)/, '') .replace(/^\w/, function(a) { return a.toUpperCase(); }); }).join(' | ') + (extra && ' | '+ extra); } 

Using this function, a header similar to this will be generated: Home | Section | Page Home | Section | Page Home | Section | Page . If you want to add certain things for a specific page, then pass the line as an extra parameter, and it will be added to the header, i.e.

 // url: http://mypage.com/home/about/frogs setTitle('Frogs are awesome'); console.log(document.title); //=> Home | About | Frogs | Frogs are awesome 
+5
source

The document object has a title property, which can be explicitly set as follows:

 document.title = "some_title_here"; 
+5
source

You can use something like (if using javascript)

 var getTitleOfPage = function(){ // logic here to work out the title of the page. }; var title = getTitleOfPage(); document.title = title; 

Alternatively, you can also use the language that is used on the server to set the name.

+2
source

Try this code in jQuery

 <script type="text/javascript"> $(document).ready(function() { document.title = 'your page title goes here'; }); </script> 
+1
source

Source: https://habr.com/ru/post/1434424/


All Articles