Recent Posts

Showing posts with label href. Show all posts
Showing posts with label href. Show all posts

HTML Best Practices: HREF attribute for JavaScript link # or javascript:void(0)

<a href="#" onclick="myJsFunc();">Run JavaScript Code</a>
<a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>
Neither is the correct way to build a JavaScript link.

If you can have an actual URL that makes sense use that as the HREF. The onclick won't fire if someone middle-clicks on your link to open a new tab or if they have JavaScript disabled.

If that is not possible, then you should at least inject the anchor tag into the document with JavaScript and the appropriate click event handlers.

I realize this isn't always possible, but in my opinion it should be striven for in developing any public website.

Check out Unobtrusive JavaScript and Progressive enhancement (both Wikipedia).

How to: Grab the href attribute from an A element

Reliable Regex for HTML are difficult. Here is how to do it with DOM:

$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $node) {
    echo $dom->saveHtml($node), PHP_EOL;
}

The above would find and output the "outerHTML" of all A elements in the $html string.

To get all the text values of the node, you do

echo $node->nodeValue; 
To check if the href attribute exists you can do

echo $node->hasAttribute( 'href' );
To get the href attribute you'd do

echo $node->getAttribute( 'href' );
To change the href attribute you'd do

$node->setAttribute('href', 'something else');
To remove the href attribute you'd do

$node->removeAttribute('href'); 
You can also query for the href attribute directly with XPath

$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//a/@href');
foreach($nodes as $href) {
    echo $href->nodeValue;                       // echo current attribute value
    $href->nodeValue = 'new value';              // set new attribute value
    $href->parentNode->removeAttribute('href');  // remove attribute
}