This is my first question here in the Stack community. I know it has been asked earlier, but I wanted to know how to do it specifically just using JS (I’m not a coder by education).
This is something what I am trying to do:
JavaScript
x
2
1
var pageTitle = document.getElementsByTagName('h1');
2
document.getElementById("demo").innerHTML = pageTitle[0].innerHTML;
JavaScript
1
9
1
<html>
2
<head>
3
<title>Update meta tag dynamically</title>
4
<meta property="og:title" content="id=demo"/>
5
</head>
6
<body>
7
<h1>First header</h1>
8
</body>
9
</html>
I know the that’s not how to use tags, just to show you what I want to do.
PS: We can’t run anything at the back-end, so it has to be in the code.
This is something else that I found, but it doesn’t work either:
JavaScript
1
11
11
1
<meta name="description" content="Old">
2
<h1>New</h1>
3
<script type='text/javascript'>
4
$(document).ready(function() {
5
var metaTitle = document.getElementsByTagName('h1');
6
// Just replacing the value of the 'content' attribute will not work.
7
$('meta[name=description]').remove();
8
$('head').append( '<meta name="description" content"$metaTitle">' );
9
});
10
</script>
11
Advertisement
Answer
Finally, cracked the code. Here it is for any future wanderers: https://github.com/idaljot/meta-tag-auto-update/blob/master/meta-tag.htm