Should I nest a var element in a code element? - html

The HTML spec states that you should contain your code samples in <code></code> elements.
An example would be:
<code>
alert('hello world');
</code>
It also states that you should contain variables in <var></var> elements.
An example would be:
<p>
A simple equation:
<var>a</var> = <var>b</var> + 2;
</p>
What if I have a variable inside the code block?
<code>
a = 10;
alert('a = ' + a);
</code>
Is it going to be like this?
<code>
<var>a</var> = 10;
alert('a = ' + <var>a</var>);
</code>
Thanks.

It's your choice whether you want to wrap it with the tag or not. there won't be any visual difference, however you like to do it.But for bot's and screen readers i'll have some special meanings. So if you need to enrich you document with proper tags, you can. It'll do without excess markups!

Related

Html <pre> not formatting/rendering text correctly [duplicate]

I'm using Prototype's PeriodicalUpdater to update a div with the results of an ajax call. As I understand it, the div is updated by setting its innerHTML.
The div is wrapped in a <pre> tag. In Firefox, the <pre> formatting works as expected, but in IE, the text all ends up on one line.
Here's some sample code found here which illustrates the problem. In Firefox, abc is on different line than def; in IE it's on the same line.
<html>
<head>
<title>IE preformatted text sucks</title>
</head>
<body>
<pre id="test">
a b c
d e f
</pre>
<script type="text/javascript"><!--
var textContent = document.getElementById("test").innerText;
textContent = textContent.replace("a", "<span style=\"color:red;\">a</span>");
document.getElementById("test").style.whiteSpace = "pre";
document.getElementById("test").innerHTML = textContent;
--></script>
</body>
</html>
Anyone know of a way to get around this problem?
Setting innerHTML fires up an HTML parser, which ignores excess whitespace including hard returns. If you change your method to include the <pre> tag in the string, it works fine because the HTML parser retains the hard returns.
You can see this in action by doing a View Generated Source after you run your sample page:
<PRE id="test" style="WHITE-SPACE: pre"><SPAN style="COLOR: red">a</SPAN> b c d e f </PRE>
You can see here that the hard return is no longer part of the content of the <pre> tag.
Generally, you'll get more consistent results by using DOM methods to construct dynamic content, especially when you care about subtle things like normalization of whitespace. However, if you're set on using innerHTML for this, there is an IE workaround, which is to use the outerHTML attribute, and include the enclosing tags.
if(test.outerHTML)
test.outerHTML = '<pre id="test">'+textContent+'</pre>';
else
test.innerHTML = textContent;
This workaround and more discussion can be found here: Inserting a newline into a pre tag (IE, Javascript)
or you could
if (el.innerText) {
el.innerText = val;
} else {
el.innerHTML = val;
}
Don't know if this has been suggested before, but the solution I found for preserving white space, newlines, etc when doing an innerHTML into a 'pre' tag is to insert another 'pre' tag into the text:
<pre id="pretag"></pre>
TextToInsert = "lots of text with spaces and newlines";
document.getElementById("pretag").innerHTML = "<pre>" + TextToInsert + "</pre>";
Seems I.E. does parse the text before doing the innerHTML. The above causes the parser to leave the text inside the additional 'pre' tag unparsed. Makes sense since that's what the parser is supposed to do. also works with FF.
It could also be rewritten 'the Python way', i.e.:
el.innerText && el.innerText = val || el.innerHTML = val;

Find first word in html and replace

I have following construct:
<h1>
<span>
</span>
</h1>
....
and
<div id="tourname">Riding trip arround the volcano</div>
Now the div with the id is filled by a php function and I would like that
my h1 looks like this:
<h1>
<span>Riding</span>
trip arround the volcano
</h1>
I managed to fill the h1 using this function:
$("h1").html($("#tourname").html());
but I have no idea how to split my string into 2 parts and fill one part
into that span and the rest behind the /span
Can you give a hint ?
Many thanks
You can do that in 2 ways .
1 - When you are writing using php , you can create the span for first word.
2 - Using jQuery. You can see the below code using jQuery
$(document).ready(function(){
var text = $("#tourname").html();
var firstword = text.substr(0,text.indexOf(' ')); // to get the first word
var remaining = text.substr(text.indexOf(' ')+1); // remianing words
var final = '<span>'+firstword+'</span> '+ remaining // combining by adding <span> around the first word
$("h1").html(final);
});
use this:
var strArr = $("#tourname").html().split(' ');
$("h1 span").html(strArr.shift());
$("h1").append(document.createTextNode(strArr.join(" ")));
This should be of some help.
Also consider this fiddle
This will be specific to your use only.
For more flexibility with number of text elements use strArr.splice(index, number_of_elements_to_include_in_span);
instead of strArr.shift();

Text should change color after # or # [duplicate]

I'm assuming it's not possible, but just in case it is or someone has a nice trick up their sleeves, is there a way to target certain characters using CSS?
For example make all letters z in paragraphs red, or in my particular case set vertical-align:sup on all 7 in elements marked with the class chord.
Hi I know you said in CSS but as everybody told you, you can't, this is a javascript solution, just my 2 cents.
best...
JSFiddle
css
span.highlight{
background:#F60;
padding:5px;
display:inline-block;
color:#FFF;
}
p{
font-family:Verdana;
}
html
<p>
Let's go Zapata let's do it for the revolution, Zapatistas!!!
</p>
javascript
jQuery.fn.highlight = function (str, className) {
var regex = new RegExp(str, "gi");
return this.each(function () {
this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
});
};
$("p").highlight("Z","highlight");
Result
That's not possible in CSS. Your only option would be first-letter and that's not going to cut it. Either use JavaScript or (as you stated in your comments), your server-side language.
The only way to do it in CSS is to wrap them in a span and give the span a class. Then target all spans with that class.
As far as I understand it only works with regular characters/letters. For example: what if we want to highlight all asterisk (\u002A) symbols on page. Tried
$("p").highlight("u\(u002A)","highlight");in js and inserted * in html but it did not worked.
In reply to #ncubica but too long for a comment, here's a version that doesn't use regular expressions and doesn't alter any DOM nodes other than Text nodes. Pardon my CoffeeScript.
# DOM Element.nodeType:
NodeType =
ELEMENT: 1
ATTRIBUTE: 2
TEXT: 3
COMMENT: 8
# Tags all instances of text `target` with <span class=$class>$target</span>
#
jQuery.fn.tag = (target, css_class)->
#contents().each (index)->
jthis = $ #
switch #.nodeType
when NodeType.ELEMENT
jthis.tag target, css_class
when NodeType.TEXT
text = jthis.text()
altered = text.replaceAll target, "<span class=\"#{css_class}\">$&</span>"
if altered isnt text
jthis.replaceWith altered
($ document).ready ->
($ 'div#page').tag '⚀', 'die'

Parse html code and set <span> tag

<div id=bar>
Hey, <b>how</b> are <span><u><b>you</b>?</u></span>
</div>
I need to parse this code and set a span tag in a determined position identified by a start and an end.
An example is: START: 15 - END: 16
(note, "start" and "end" are set from the simple string "Hey, how are you?")
<div id=bar>
Hey, <b>how</b> are <span><u><b>y<span id=someid>ou</span></b>?</u></span>
</div>
My idea is to parse the node "bar", getting its html code, and with a complex OOP algoritm set the span tag, but...it's hard and long to do. (everything in JS)
Is there a good programming language to semplify my work?
I think I get what you are trying to do. Try this out:
var text = $("#bar").text(); //jQuery gives you the text...strips the html tags
var html = $("#bar").html(); //jQuery gives you the html and text here
text = $.trim(text); //remove any whitespace from start and end
var original = text.substr(14, 2); //Get the substring you want
var updated = "<span id='someid'>" + original + "</span>";
html = html.replace(original, updated); //replace
$("#bar").html(html); //set new html
JsFiddle here: http://jsfiddle.net/bbcLm97o/2/

highlight words in html using regex & javascript - almost there

I am writing a jquery plugin that will do a browser-style find-on-page search. I need to improve the search, but don't want to get into parsing the html quite yet.
At the moment my approach is to take an entire DOM element and all nested elements and simply run a regex find/replace for a given term. In the replace I will simply wrap a span around the matched term and use that span as my anchor to do highlighting, scrolling, etc. It is vital that no characters inside any html tags are matched.
This is as close as I have gotten:
(?<=^|>)([^><].*?)(?=<|$)
It does a very good job of capturing all characters that are not in an html tag, but I'm having trouble figuring out how to insert my search term.
Input: Any html element (this could be quite large, eg <body>)
Search Term: 1 or more characters
Replace Txt: <span class='highlight'>$1</span>
UPDATE
The following regex does what I want when I'm testing with http://gskinner.com/RegExr/...
Regex: (?<=^|>)(.*?)(SEARCH_STRING)(?=.*?<|$)
Replacement: $1<span class='highlight'>$2</span>
However I am having some trouble using it in my javascript. With the following code chrome is giving me the error "Invalid regular expression: /(?<=^|>)(.?)(Mary)(?=.?<|$)/: Invalid group".
var origText = $('#'+opt.targetElements).data('origText');
var regx = new RegExp("(?<=^|>)(.*?)(" + $this.val() + ")(?=.*?<|$)", 'gi');
$('#'+opt.targetElements).each(function() {
var text = origText.replace(regx, '$1<span class="' + opt.resultClass + '">$2</span>');
$(this).html(text);
});
It's breaking on the group (?<=^|>) - is this something clumsy or a difference in the Regex engines?
UPDATE
The reason this regex is breaking on that group is because Javascript does not support regex lookbehinds. For reference & possible solutions: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript.
Just use jQuerys built-in text() method. It will return all the characters in a selected DOM element.
For the DOM approach (docs for the Node interface): Run over all child nodes of an element. If the child is an element node, run recursively. If it's a text node, search in the text (node.data) and if you want to highlight/change something, shorten the text of the node until the found position, and insert a highligth-span with the matched text and another text node for the rest of the text.
Example code (adjusted, origin is here):
(function iterate_node(node) {
if (node.nodeType === 3) { // Node.TEXT_NODE
var text = node.data,
pos = text.search(/any regular expression/g), //indexOf also applicable
length = 5; // or whatever you found
if (pos > -1) {
node.data = text.substr(0, pos); // split into a part before...
var rest = document.createTextNode(text.substr(pos+length)); // a part after
var highlight = document.createElement("span"); // and a part between
highlight.className = "highlight";
highlight.appendChild(document.createTextNode(text.substr(pos, length)));
node.parentNode.insertBefore(rest, node.nextSibling); // insert after
node.parentNode.insertBefore(highlight, node.nextSibling);
iterate_node(rest); // maybe there are more matches
}
} else if (node.nodeType === 1) { // Node.ELEMENT_NODE
for (var i = 0; i < node.childNodes.length; i++) {
iterate_node(node.childNodes[i]); // run recursive on DOM
}
}
})(content); // any dom node
There's also highlight.js, which might be exactly what you want.