Using the this keyword, means that we pass into the function a reference to the link. That way the addText function can easily gain a reference to the correct link, even if the onclick event is used on multiple links.
Some web browsers differ in how they provide the href value, so it’s best to split the href value at the # symbol, and then take the second part of it (at index 1).
function addText(el) {
var targetId = el.href.split('#')[1];
var target = document.getElementById(targetId);
...
}
A more modern technique is to not have the scripting intermingled with the HTML code, and to allow the page to work properly even when there is no scripting available.
<div id="textTarget"></div>
Because the add text link is only be useful when scripting is available, it is added with scripting. We can even take the time to add an addTarget property onto the link, so that we can easily get back to the target.
var targetId = 'textTarget';
var target = document.getElementById(targetId);
var a = document.createElement('a');
a.href = '#' + targetId;
a.innerHTML = '+ Add Text';
a.addTarget = target;
a.onclick = addText;
target.parentNode.insertBefore(a, target);
Then from the addText function, the link is accessible via the this keyword
function addText() {
var link = this;
var target = link.addTarget;
...
}