0

I need to write a regular expression which will look a div element with an ID="test1" in html and if it does not find it only then it should look for div element with ID="test2"

e.g.

<div id="test1">
some stuff inside test1
</div>

<div id="test2">
some stuff inside test2
</div>

if div id="test1" is present then i need the text "some stuff inside test1". if there is no div with id="test1" only then it should look div with id="test2" and get me the text inside "test2" which is in this case "some stuff inside test2"

  • 6
    In before ***[HE COMES](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)*** –  Apr 18 '11 at 15:06
  • 3
    If you'd explain your problem instead of a possible solution we might be able to come up with a better answer. – Niklas Apr 18 '11 at 15:10
  • Although I agree with Niklas, I've left an answer, that may help you. We really need to know what you're doing, what the big picture is. – Josh Apr 18 '11 at 15:15

2 Answers2

0

Can it be done after page load? Like, with Javascript? If it doesn't have to be pre-processed, you can do it like so: (jQuery)

$(document).ready(function(){

  // does test1 exist?
  if( $("#test1").length > 0 ){
    $("#test1").html("some stuff goes in here");
  }

  // does test2 exist?
  if( $("#test2").length > 0 ){
    $("#test2").html("some stuff goes in here");
  }

});

If that doesn't work, you can try doing a string search in whatever language you're using before you output the HTML.

Josh
  • 12,448
  • 10
  • 74
  • 118
0

Just wondering, why dont you do the following?

var returnVal;
if(document.getElementById("test1"))
    returnVal = document.getElementById("test1").innerHTML;
else if (document.getElementById("test2"))
    returnVal = document.getElementById("test2").innerHTML;
else
    returnVal = "no value found";

But still, if you wish to that by regex something similar is possible:

var divs = document.body.innerHTML, returnVal = "", ids = new Array();
ids.push("test1");
ids.push("test2");
    for (var i = 0; i < ids.length; i++) {
         var toBeFound = "<div(.*?)id=(\"|\')" + ids[i] + "(\"|\')(.*?)>";
         var newRegex = new RegExp(toBeFound, "i");
         var match = divs.match(newRegex);
         if (match.length > 0) {
             returnVal += document.getElementById(ids[i]).innerHTML + ",";
         }
    }

This code scans all the document. For each id provided in the ids array, the code will search for divs with an id of the current array element. If it will find then it will add the innerHTML of the relevant div in the returnVal string, and each value will be seperated by commas. However, I strongly recommend the first code.

Shaokan
  • 7,438
  • 15
  • 56
  • 80