views:

201

answers:

3

I am trying to first find a div using a regular expression (since its class name is somewhat dynamic).

Once found, I then need to place the div inside of a fieldset, so I end up having a final output of

<fieldset class="...">
    <div class="the one I found">...</div>
</fieldset>

How can I do this in javascript?

Much thanks, Steve

+3  A: 

This is going to be difficult to do with regexes and ill-advised. For example, what if the div contains other divs? Finding the correct closing div tag is not something a regular expression can do because HTML is not a regular language.

On the other hand, this is a trivial one liner with jQuery:

$("div.someClass").wrap("<fieldset class='...'></fieldset>");

It can of course be done with vanilla Javascript DOM using something like:

var divs = document.getElementsByTagName("div");
for (var i=0; i<divs.length; i++) {
  if (divs[i].className == "...") {
    var fs = document.createElement("fieldset");
    fs.className = "...";
    var parent = divs[i].parentNode;
    parent.insertBefore(fs, divs[i]);
    fs.appendChild(divs[i]);
  }
}

You of course need to fill in what class to put on the fieldset and change the test on the div to figure out if you need to manipulate it or not.

cletus
The div most definitly will contain other div's. I need to copy it, and all of its subelements into a fieldset. How can I find the name of "someClass" using a regular expression?
Steven1350
A: 

using jquery, you can try this:

var classes = $(document.body).html().match(/class="pattern"/g); // find classname matchin pattern 
for(i in classes) {
  var nodes = $('.'+classes[i].substr (7, str.length - 8));
  nodes.wrap("<fieldset class='...' />");
}
mathroc
A: 
   window.onload = function() {

        var params = {
            has: "something"
        };

       // var fieldset = doc... get field the same as with div. 

        var divs = document.getElementsByTagName("div");
        for (var i = 0; i < divs.length; i++) {
            if (params.has.indexOf(divs[i].className) > 0) {
             //  fieldset.innerHTML  = divs[i].innerHTML;
               divs[i].innerHTML = "<fieldset class=''> + divs[i].innerHTML + "</fieldset>"; 
            }
        }

    }

No need to use regular expression, indexof method is sufficient. And no need to use jquery. Javascript has good string and array functions - use them, but the DOM is a mess.

poo