views:

43

answers:

2

i am using the following code snippet to fetch element with a particular id but it kind of messes up at times... Does anyone have a better code...? or fix for this?

function getData(html,id){

  var curSectionId = id;
  var subStr=html.substring(html.indexOf("id=\""+curSectionId+"\""),html.length-1);
  var divsStrs=subStr.split("<div");
  var divSec="";
  var opeDiv=0;
  for(var count=0;count<divsStrs.length;count++)
  {
    if(divsStrs[count].indexOf("</div>")!=-1 && divsStrs[count].indexOf("</div>")!=(divsStrs[count].lastIndexOf("</div>")))
    {
      opeDiv++;
      var lDiv=divsStrs[count].split("</div>");
      var lString="";
      var totalJcount;

      for(var jcount=0;jcount<=opeDiv;jcount++)
      {
        lString=lString+lDiv[jcount]+"</div>";
        opeDiv--;
      }

      divSec=divSec+"<div "+lString;
      break;
      } else if (divsStrs[count].indexOf("</div>")!=-1 )
      {
        divSec=divSec+"<div "+divsStrs[count];
        opeDiv++;

        if(opeDiv==0)
        {
          break;
          }else
          {
            opeDiv--;
            continue;   
          }
        }

        divSec=divSec+"<div "+divsStrs[count];
        opeDiv++;
      }
      return divSec;
    }
+4  A: 

Try document.getElementById

Tom
+1 lol yep. First thing that poped my mind too.
Yves M.
A: 

You should really consider using jQuery or something similar. Would make the code much ligther.

Yves M.