In HTML 4.0 Strict and XHTML 1.0 STRICT, the target attribute is not allowed in the <a> tag, which is a frustrating thing for web designers. It is still allowed to be used in transitional specifications. But through certain methods, we can solve this problem.
The target attribute was removed from the HTMl4.0 specification: but it added another attribute: rel. This attribute is used to specify the relationship between the document containing the link and the linked document. Its attribute values (such as: next, previous, chapter, section) are defined in the specification. Most of these attributes are used to define relationships between small parts of a large document. In fact, the specification allows developers to freely use non-standard property values for specific applications.
Here, we use a custom value external for the rel attribute to mark a link to open a new window.
Link code that does not comply with the latest web standards:
<a href="document.html" target="_blank">external link</a>
Use the rel attribute:
<a href="document.html" rel="external">external link</a>
Now that we have constructed a link to a new window that complies with Web standards, we also need to use JavaScript to implement a new window. What the script wants to do is to find all the hyperlinks in the document that we define as rel="external" when the web page loads.
First we need to determine the browser
if (!document.getElementsByTagName) return;
getElementsByTagName is an easy-to-use method in the DOM1 standard, and it is supported by most browsers now. Because some old browsers such as Netscape 4 and IE4 do not support DOM1, we must rule it out by determining whether this method exists. these older versions of browsers.
Next, we obtain all <a> tags in the document through the getElementsByTagName method:
var anchors = document.getElementsByTagName("a");
Anchors are assigned as an array containing each <a> tag. Now we must loop through each <a> tag and modify it:
for (var i=0; i < anchors.length; i++) {
var anchor = anchors;
Find the <a> tag where you want to open a new window
if (anchor.getAttribute("href") &&
anchor.getAttribute("rel") == "external")
Next, create the attribute value target and assign the value "_target"
anchor.target = "_blank",
Complete code:
function externalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i=0; i<anchors.length; i++) {
var anchor = anchors;
if (anchor.getAttribute("href") &&
anchor.getAttribute("rel") == "external")
anchor.target = "_blank";
}
}
window.onload = externalLinks;