javascript - Get Attributes of enclosing Tag in HTML String -
javascript - Get Attributes of enclosing Tag in HTML String -
i working on simple text screen / terminal emulator (similar jquery terminal plugin, without rpc stuff , window functionality). each line of screen table row (a html string) , print command can insert text attributes (e.g. foreground , background color). each printed text enclosed span style attributes, example:
<span style="color:#000000;background-color:#111111">a</span><span style="color:#222222;background-color:#333333>bc</span>
this works fine. want add together function gives me attributes of character @ given screen position, in above line character @ position 0 (a) has color #000000. have count characters don't belong span tag , lastly preceding styles. first rather error prone solution is:
function getattr(line, position) { var result = {foreground:'', background:''}, ch = '', i, j = -1, tag = false; // count characters (i = 0; < line.length && j < position; i++) { ch = line.charat(i); if (ch == '<') { tag = true; } if (ch == '>') { tag = false; } else if (!tag) { j++; } } i--; // find styles while (i > 0 && line.charat(i) != '<') { if (line.substr(i, 6) == 'color:') { result.foreground = line.substr(i + 6, 7); } if (line.substr(i, 17) == 'background-color:') { result.background = line.substr(i + 17, 7); } i--; } homecoming result; }
is there simpler solution without counting characters (maybe jquery or regex)?
this similar get parent element of selected text don't need selection, character index.
a possible way handle building info construction allows index each line , @ character , it's associated styles done using next snippet each line. assumes markup you're generating html shown above stable (you business relationship variations in regex if needed):
var tagre = /\<span style="([^"]+)"\>([a-za-z]+)\<\/span\>/ig, s = '<span style="color:#000000;background-color:#111111">a</span><span style="color:#222222;background-color:#333333">bc</span>'; var matches, positions = []; while (matches = tagre.exec(s)) { var len = matches[2].length, chars = matches[2], styles = {}; matches[1].split(';').foreach(function(o) { var _s = o.split(':'), key = _s[0], val = _s[1]; styles[key] = val; }); (var i=0; < len; i++) { var char = chars[i]; positions.push({ 'char': char, 'styles': styles }); } } console.log("positions=%o", positions);
this give array each line looks following:
[ { char: 'a', styles: { 'background-color': '#111111', 'color': '#000000' } }, { char: 'b', styles: { 'background-color': '#333333', 'color': '#222222' } }, { char: 'c', styles: { 'background-color': '#333333', 'color': '#222222' } } ]
that allow index each line integer character position , character @ position along associated styles object.
javascript string screen
Comments
Post a Comment