What is target attribute in HTML: Definition and Usage
target attribute in HTML specifies where to open the linked document or resource when a user clicks a link. It is commonly used with <a> tags to open links in the same tab, a new tab, or a specific frame.How It Works
The target attribute tells the browser where to display the page you want to open when clicking a link. Think of it like choosing which window or tab to open a new page in. By default, links open in the same tab, but with target, you can change this behavior.
For example, if you want a link to open in a new tab, you set target="_blank". This is like telling the browser, "Please open this link in a fresh window or tab." Other values let you open links in named frames or the same frame, which was more common when web pages used frames.
Example
This example shows three links: one opens in the same tab, one opens in a new tab, and one opens in a named frame (if frames were used).
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Target Attribute Example</title> </head> <body> <h2>Links with Different target Attributes</h2> <ul> <li><a href="https://example.com" target="_self">Open in same tab (default)</a></li> <li><a href="https://example.com" target="_blank" rel="noopener noreferrer">Open in new tab</a></li> <li><a href="https://example.com" target="myframe">Open in named frame (if exists)</a></li> </ul> </body> </html>
When to Use
Use the target attribute when you want to control where a link opens. For example, opening external websites in a new tab (target="_blank") keeps your site open for users. This is helpful for links to other sites, documents, or resources.
Also, if your site uses frames or iframes, target can specify which frame to load the link into. However, frames are less common today.
Key Points
- _self opens link in the same tab (default behavior).
- _blank opens link in a new tab or window.
- _parent opens link in the parent frame.
- _top opens link in the full body of the window.
- Named targets open links in specific frames or iframes.