I am trying to scan my page on document load and convert all links as hyperlinks. This is saying 'x' is null. Can you suggest me how to do this in jquery. I am not sure if .re开发者_如何学PythonplaceWith works
var x = document.getElementById('body');
x.innerHTML = x.innerHTML.replace(/(http:\/\/[^ ]+)/g,'<a href="$1">$1</a>/');
You already have access to the body via:
var x = document.body;
No need for a method.
Though there are better ways to create links than to destroy and recreate the entire DOM. Also, this will affect elements that currently have an href
attribute starting with http
.
EDIT: This is a less destructive way to accomplish what you want:
var re = /(http:\/\/[^ ]+)/g;
function createLinks( els ) {
$(els).contents().each( function() {
if( this.nodeType === 1 && this.nodeName !== 'script' ) {
createLinks( this );
} else if( this.nodeType === 3 && this.data.match( re ) ) {
var markup = this.data.replace( re, '<a href="$1">$1</a>' );
$( this ).replaceWith( markup );
}
});
}
createLinks( document.body );
Example: http://jsfiddle.net/dVsqe/
Or no jQuery:
var re = /(http:\/\/[^ ]+)/g;
var temp = document.createElement('div');
function createLinks( els ) {
var nodes = els.childNodes, node;
for( var i = 0; i < nodes.length; i++ ) {
node = nodes[ i ];
if( node.nodeType === 1 && node.nodeName !== 'script' ) {
createLinks( node );
} else if( node.nodeType === 3 && node.data.match( re ) ) {
temp.innerHTML = node.data.replace( re, '<a href="$1">$1</a>' );
while( temp.firstChild ) {
node.parentNode.insertBefore( temp.firstChild, node );
}
node.parentNode.removeChild( node );
}
};
}
createLinks( document.body );
Example: http://jsfiddle.net/dVsqe/2/
body
is not the 'id' of the body element; it's the tag-name or, in JavaScript, the tagName
. Therefore you should use the appropriate JavaScript method getElementsByTagName()
. As this returns (potentially) a number of elements, you have to specify which of the returned elements you want to work with, in this case the first (and only, I'd imagine), which in JavaScript is the zero-th, so instead you should use:
var x = document.getElementsByTagName('body')[0];
References:
.getElementsByTagName()
at Mozilla Developer Center.
in jQuery
$('body').html( $('body').html().replace(/(http:\/\/[^ ]+)/g,'<a href="$1">$1</a>/'));
精彩评论