Markdown anchors with target="_blank"
Markdown parsing of anchors <a>
don't account for extra attributes like:
target="_blank"
rel="nofollow"
Add JavaScript to MarkdownExtra to make anchors with target="_blank"
and/or rel="nofollow"
.
MarkdownExtra
I installed Parsedown and ParsedownExtra libraries on this website. They are a PHP library that executes the MarkdownExtra extension.
cd ~/Code/blog.stemar.net
git clone --depth=1 https://github.com/erusev/parsedown.git vendor/parsedown
git clone --depth=1 https://github.com/erusev/parsedown-extra.git vendor/parsedown-extra
This allows to introduce Special Attributes in curly bracket at the right of an HTML element. Example:
[ParsedownExtra](https://github.com/erusev/parsedown-extra){.target-blank}
After Markdown parsing, this will translate to:
<a href="https://github.com/erusev/parsedown-extra" class="target-blank">ParsedownExtra</a>
Code
I put this JavaScript code in /assets/js/init.js
that loads on every page on this website.
- It looks for anchors with the class
target-blank
andrel-nofollow
. - It adds the attribute
target="_blank"
andrel="nofollow"
to these elements. - It removes the class name.
- It removes the class attribute if it's left blank.
(function(d) {
var attrs = [
['target-blank', 'target', '_blank'],
['rel-nofollow', 'rel', 'nofollow']
];
attrs.forEach(function(attr) {
d.querySelectorAll('.' + attr[0]).forEach(function (e) {
e.setAttribute(attr[1], attr[2]);
e.classList.remove(attr[0]);
if (e.className == '') e.removeAttribute('class');
});
});
})(document);
Result
You can see the result in an Inspect window in a browser but it doesn't appear in View Source.
This:
[ParsedownExtra](https://github.com/erusev/parsedown-extra){.target-blank}
Becomes this:
<a href="https://github.com/erusev/parsedown-extra" target="_blank">ParsedownExtra</a>