chessofnerd
chessofnerd

Reputation: 1279

Altering HTML with attributes using jQuery

I've been looking for a way to use jQuery to translate HTML. For instance, I would like to change

<myTag name1="sally" name2="billy" datingFor="3" />
<myTag name1="jill" name2="tom" datingFor="4" />

to another form such as

<div>SALLY has been dating BILLY for 3 months</div>
<div>JILL has been dating TOM for 4 months</div>

using a jQuery function that executes after the document is ready.

Is there an easy way to do this? I know I can use something like $('#div').html('New Text') but this approach doesn't seem applicable when I have parameters (such as the name or datingFor fields).

Upvotes: 0

Views: 52

Answers (3)

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

Try this:

$('myTag').each(function() {
    var $this = $(this),
        name1 = $this.attr('name1'),
        name2 = $this.attr('name2'),
        dating = $this.attr('datingFor');

    $this.replaceWith($('<div/>').text(name1 + ' has been dating ' + name2 + ' for ' + dating + ' months'));
});

Working demo: http://jsfiddle.net/92ctS/ but I had to modify the tags from <myTag/> to <myTag></myTag> to have it work on Firefox.

This works with original tags though: http://jsfiddle.net/92ctS/1/

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388436

Try

$('myTag').replaceWith(function () {
    var $this = $(this);
    return '<div>' + $this.attr('name1') + ' has been dating ' + $this.attr('name2') + ' for ' + $this.attr('datingFor') + ' months</div>'
})

Update: Since the OP has a string

var string = '<myTag name1="sally" name2="billy" datingFor="3" /><myTag name1="jill" name2="tom" datingFor="4" />';

var list = $(string).map(function () {
    var $this = $(this);
    return '<div>' + $this.attr('name1') + ' has been dating ' + $this.attr('name2') + ' for ' + $this.attr('datingFor') + ' months</div>'
}).get();

$('body').append(list.join(''))

Demo: Fiddle

Upvotes: 1

Venkata Krishna
Venkata Krishna

Reputation: 15112

jsFiddle Demo

var myTags = $('myTag');

myTags.each(function(i){
    var name1 = $(this).attr('name1');
    var name2 = $(this).attr('name2');
    var datingFor = $(this).attr('datingFor');
    $('.container').append('<div>' + name1 + ' has been dating '+ name2 + 'for '+ datingFor + ' months</div>');
    //$(this).replaceWith('<div>' + name1 + ' has been dating '+ name2 + 'for '+ datingFor + ' months</div>');
});

If you want to replace the existing myTag with the generated div.Use .replaceWith() instead of .append().

Upvotes: 1

Related Questions