0

Does anybody know a way for matching Selection object with HTML dom elements based on something else than the element value?

Let's consider the table below:

123 | 246 | 345

456 | 123 | 567

The user wants to modify the first row by selecting it with mouse. In javaScript I can match the

window.getSelection().toString().split("\t")

with

document.getElementsByTagName("td") 

to find thet selected cells. But for that matching I haven't found any other means than combining the element values (innerHTML). This will mean that all cells with the same value ( in the example the second column on the second line) become modified althoug not chosen. My code for reference:

function setAsNumeric(selection){    
var allTds = document.getElementsByTagName("td");
var results = [];
var selArray = selection.toString().split("\t").join("\r\n").split("\r\n")
for ( var i = 0; i < selArray.length; i++ ) {
    for ( var x=0; x < allTds.length; x++ ){
        if ( allTds[x].innerHTML == selArray[i] ){
            results.push(allTds[x]);
        }    
    }
}
var n;
for (i = 0; i < results.length; i++){
    n = document.createElement("td");
    n.innerHTML = results[i].innerHTML;
    n.className = "number";
    results[i].parentNode.insertBefore(n, results[i]);
    results[i].parentNode.removeChild(results[i]);
    }
}
Jaana
  • 266
  • 1
  • 3
  • 14
  • What do you want to achieve by doing this? I don't understand why you need that kind of match. – Andrei Rosu Aug 10 '18 at 05:58
  • I'm creatiung a table tool for users. The users are going to copy-paste excel-files into my web page and add/modify some HTML tags (thead, tfood, td - > th, etc.). For instance the users should be able to define selected cells as row headers. I'm now afraid, that it would be possible, in a big table, to have the same value in two cells but the user would like to define only the selected one as a row header. – Jaana Aug 10 '18 at 08:23
  • Actually I just found a solution that solves the problem of affecting a non-selected cell that thas the same innerHTML with a selected one: function inSelection(elem) { var range; var sel = window.getSelection(); for (var r=0; r < sel.rangeCount; r++){ range = sel.getRangeAt(r); if (range.intersectsNode(elem)){ return true; }; } return false; } – Jaana Aug 13 '18 at 06:34
  • Even though the above solves my problem I'm still looking forward for an eleagnt solution, thus keeping my question still open. – Jaana Aug 13 '18 at 06:41

0 Answers0