In a xhtml, i want to highlight the text between two self closing tags s1 and s2 whose attribute "ind" has the same value. Eg. <s1 ind="1"/>
and <s2 ind="1" />
Eg.
<html>
<body>
<a>
<b>
Some <s1 ind="1"/> text
></b>
<c>
data <s2 ind="1"/>
here</c>
</a>
</body>
</html>
I want "text data" to get highlighted. Is is possible to achieve using javascript/jquery? I could have many such self closing tag pairs s1 and s2 with a unique value for "ind" for the pair indicating that the text within them needs to be highlighted.
views:
94answers:
2There is no such thing as "custom tags" in (X)HTML. You can't just make up tags. They may work in some browsers, but its not something you should rely on. Use "normal" tags such as div
and span
with a class.
EDIT: Ok, I think I get what you want now. However you still can't use custom elements nor self-closing ones - especially if you need to support IE, since it doesn't support either. You'll need to use empty elements instead, such as:
<html><body><a><b>Some <span id="s1-1"></span> text></b> <c>data <span id="s2-1"></span>here</c> </a></body></html>
What you need to do then is traverse the document tree starting with <span id="s1-1"></span>
and ending with <span id="s2-1"></span>
and "wrap" all textnodes found on the way with span
s and a class you can use to highlight.
Something like this (untested, from the top of my head and most likely wrong because I'm tired):
function wrapUntil(element, nr) {
if (element.id === "s2-" + nr)
return;
if (element.nodeType === 3) {
var span = document.createElement("span");
span.className = "highlight-" + nr;
element.parentNode.replaceChild(span, element);
span.appendChild(element);
element = span;
} else {
var child = element.firstChild;
if (child) {
wrapUntil(child, nr);
}
}
var sibling = element.nextSibling();
if (sibling)
wrapUntil(sibling, nr);
else
wrapUntil(element.parentNode(), nr);
}
wrapUntil(document.getElementById("s1-1"), "1");
BTW, depending on where and how you get your data, this may be something you should be doing server-side instead of with JavaScript.
instead of using your "custom tags" you should use a span
or div
with a class named highlight
:
<span class="highlight">This text is highlighted</span>
with CSS you can format your highlighted text however you want:
.highlight { background-color:yellow; font-weight:bold }
with jQuery you can add or remove the highlight
class:
$('span').addClass('highlight')
$('span').removeClass('highlight')
EDIT: now I got your problem.
The answer is No, you can't hightlight a text spanning accross other html tags, like this:
This <b>code <span class="highlight">will</b> not</span> work
You have to close the span tag before </b>
and open it up again after it:
This <b>code <span class="highlight">will</span></b>
<span class="hightlight"> work</span> very well.