I am trying to execute a simple search and highlight function in Javascript that searches for a piece of text. The XHTML tag with which that piece of text occurs is also given as an argument for additional help in locating that text.
The XHTML that I am testing this function out on:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="application/xml+xhtml;charset=UTF-8" />
<script src="searcher.js" type="text/javascript"></script>
<script src="jquery-2.0.2.min.js"> </script>
<title>Building your resume</title>
</head>
<body id="highlightbegin">
<h1>Building your resume</h1>
<div> <input name="input" type="button" value="Highlight3" onclick="javascript:searcher('<h1>','Building your resume', '<h1>Building your resume', 'resume');" /> </div>
</body>
</html>
The function searcher in searcher.js:
function searcher(tag, text, tagText, word) {
//simple search.
console.info(word + " to be searched for in " + text + " with tag text = " + tagText);
//get old html.
var oldHTML = document.getElementById("highlightbegin").innerHTML;
//get regexp.
var regexp = new RegExp(tagText, 'g');
var match = oldHTML.match(regexp);
console.info(text + " found " + match.length + " times.");
}
However, executing the RegExp, match returns null. Further investigation reveals that the tag <h1>Building your resume</h1> becomes <h1 xmlns="http://www.w3.org/1999/xhtml">Building your resume</h1> which causes the match function to return null. My questions:
- Why is the
xmlnsattribute added automatically? - Is there a way to prevent the attribute from being added?
- What tags will that attribute be added to? Is it safe to assume that it will be added to every tag?
- Is this a browser-specific issue or can this behavior be expected in all browsers?
EDIT:
An observation:
1. If I add the xmlns attribute to the body tag and access all content with outerHTML (var oldHTML = document.getElementById("highlightbegin").outerHTML;), its child elements do not have the xmlns attribute.
My questions:
1. Can the outerHTML element be edited (with Javascript) and replaced?
2. Is the observation above consistent (seen each time outerHTML is invoked) or is it implementation dependent?
3. Is it Javascript that adds the xmlns attribute automatically or the browser?