Comparing strings with DOM elements

This problem confused me for a bit and may be of some help to someone in the future.  What I was trying to do was compare a javascript string with an existing DOM element (Don’t ask why).

Anyways, normal text is no problem, the problem is that when HTML tags are entered into the DOM it is modified to work properly. Inserting a table or input element gets modified in its own way.

  • Tables get tbody tags if none exist
  • input buttons get organized by value,onclick,type (only ones tested)

Therefore matching the HTML string with the DOM after it’s changed will tell you they aren’t equal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function compare2Strings(str,str2){
    alert('string 1 : '+str+', string 2 : '+str2);

    if(str.length != str2.length){
        alert('different lengths :'+str.length+'/'+str2.length);
    }
   
    for(i=0;i<str.length;i++){
            if(str.length < i || str2.length < i){
                return false;
            }

        if(str.charAt(i) != str2.charAt(i)){
            alert('character at position '+i+' is different :'+str.charAt(i)+'/'+str2.charAt(i));
        }
    }
}

This function is pretty crude, but showed me what was wrong. Hopefully if this is what you are looking for, it helps you with your project.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>