tags:

views:

344

answers:

5

Hey everyone,

what I want to do: call an unload-function to change

<span>some content</span>

into

<label>some content</label>

Is it possible to change a span-tag into a label-tag with javascript? If it is possible how can I do that?

Thnx,

... doro

+1  A: 

You can use the replace(). More info here

I'm not very good at RegExp, so I can't tell you exactly what to write, but something along the lines of:

var divHTML = getElementById("myDiv"); //The div which contains your spans
divHTML.innerHTML.replace(/<span>/gi, "<label>");
divHTML.innerHTML.replace(/<\/span>/gi, "</label>");

Please don't bust me on this, though :p

edit: If you want to maintain class names, ids and such, you simply leave out the right-angle-bracket:

divHTML.innerHTML.replace(/<span/gi, "<label");

This will turn <span id="mySpan" class="spans"> into <label id="mySpan" class="spans">

peirix
+1  A: 

And if you're using jQuery you can use replaceWith()

jQuery.each($("span"), function() {
  $(this).replaceWith("<label>" + $(this).text() + "</label>");
});

More information at: http://docs.jquery.com/Manipulation/replaceWith

Andrew Mason
short and easy!!! THNX :)
doro
+1  A: 

First you need to gain a reference to the SPAN element, then you can go about replacing it with a new element:

HTML:

<span id="something">Content</span>

JavaScript:

var span = document.getElementById('something');
var label = document.createElement('label');
label.innerHTML = span.innerHTML;
span.parentNode.replaceChild( label, span );
J-P
but i had to give every span i want to convert the id "something", right?
doro
you won't want to give the same id to multiple elements. But you could give all spans you want to change a class name. Then do `document.getElementsByClassName("changeSpan");`, and loop through them and run the code by J-P on each element.
peirix
A: 
document.body.innerHTML = 
    document.body.innerHTML.
         replace(/<span>/g, '<label>').
         replace(/<\/span>/g, '</label>');
RaYell
doesn't work ... sorry
doro
There was a tiny error, but this definately works
RaYell
+2  A: 

(Using jQuery) If you need to maintain the classes between the conversion:

$("span").each(function(){
    so_classes = $(this).attr("class");
    so_value = $(this).html();
    so_newLabel = $("<label></label>").html(so_value);
    if (so_classes.length > 0) {
     $(so_newLabel).attr("class",so_classes);
    }
    $(this).replaceWith(so_newLabel);
});

Converts this

<span>Hello World</span>
<span class="bigger"><strong>Hello World!</strong></span>
<span class="big blue">Hello, <em>World</em>.</span>

Into this

<label>Hello World</label>
<label class="bigger"><strong>Hello World!</strong></label>
<label class="big blue">Hello, <em>World</em>.</label>
Jonathan Sampson
thnx! looks good. i'll try that!
doro
Copying/modifying the so_classes line, you can maintain id values too.
Jonathan Sampson