Jesse Atkinson
Jesse Atkinson

Reputation: 11406

How do I change a DOM element?

I want to use javascript to change all of the <option> tags to <a> tags. I want all of the attributes to stay the same. I simply want to do a switch on what type of tag it is.

I tried doing several variations on this idea but to no avail.

$.each (array_of_options, function (i, v) {
    v.replace(/option/i, "a");
});

But this has returned nothing but errors.

Upvotes: 0

Views: 126

Answers (2)

David Thomas
David Thomas

Reputation: 253308

One option:

$('option').each(
    function(){
        var that = $(this);
        $('<a />')
            .text(that.text())
            .attr('href','#' + that.val() + '.html')
            .appendTo($('body'));
        that.remove();
    });

JS Fiddle demo.

Or, you could use plain JavaScript:

var sel = document.getElementById('select'),
    opts = sel.getElementsByTagName('option'),
    b = document.getElementsByTagName('body')[0];

for (var i=0,len=opts.length;i<len;i++){
    var a = document.createElement('a');
    a.href = '#' + opts[i].value + '.html';
    a.innerHTML = opts[i].innerHTML;
    b.appendChild(a);
}

JS Fiddle demo.

Upvotes: 2

Robert Messerle
Robert Messerle

Reputation: 3032

I created a quick jsFiddle for this: http://jsfiddle.net/KkGUt/

This creates a new tag, copies over the text, copies over the attributes, then replaces the original tag.

Code:

$( function () {
    $( 'option' ).each( function () {
        var $old  = $( this ),
            $new  = $( document.createElement( 'a' ) ),
            attrs = $old.get( 0 ).attributes;
        //-- copy text from option
        $new.text( $old.text() );
        //-- copy over attributes
        for ( var i = 0, len = attrs.length; i < len; i++ ) {
            $new.attr( attrs[ i ].name, attrs[ i ].nodeValue );
        }
        //-- replace $old with $new
        $old.replaceWith( $new );
    } );
    console.log( $( 'form' ) );
} );​

Upvotes: 0

Related Questions