Reputation: 84
My site starts with a class.page.php constructor/destructor that contains the meta info, page title and footer.
<?php
class page{
private $title;
private $pageDescription;
public function __construct($title, $pageDescription){
$this->title = $title;
$this->pagedescription = $pageDescription;
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
<meta name="description" content="My Page Description;">
// … etc …
function __destruct()
{
// … etc …
}
}
?>
Each page begins with this PHP script to require the class.page.php and insert that page's title and description into the head.
<?php
require_once("inc/class.page.php");
// Insert title, page description.
$page = new page('My Page Title','My Page Description');
?>
My goal is to be able to insert the description content from the meta tag…
<meta name="description" content="I want this also to show up between the h2 tags.">
…in between the h2
tags in the body text, i.e.:
<h2>How do I insert the page description here?</h2>
I'm able to get the page title to show between the h1
tags as shown below, but I haven't been able to figure out how to do something similar with the meta description content.
<h1 id="pagetitle"></h1>
<script>
document.getElementById('pagetitle').innerHTML = document.title;
</script>
I would prefer to find a PHP solution for this (and for the page title, too, for that matter). but I'd also be happy also to do this using JavaScript.
Upvotes: 2
Views: 58
Reputation: 370679
You can select a <meta name="description">
element with a meta[name=description]
selector:
const content = document.querySelector('meta[name=description]').getAttribute('content');
document.getElementById('pagetitle').textContent = content;
<meta name="description" content="I want this also to show up between the h2 tags.">
<h1 id="pagetitle"></h1>
Also remember to only use innerHTML
when deliberately inserting HTML markup - if you only want to insert text, use textContent
instead. (innerHTML
is less appropriate, slower, and can allow for arbitrary code execution if the content being set isn't trustworthy)
Upvotes: 1