petko_stankoski
petko_stankoski

Reputation: 10713

Change outerHTML in javascript or jquery

I want to change the outerHTML and this is what I do:

$(data.description)[0].outerHTML = $(data.description)[0].outerHTML.replace('red', 'black');

The value is:

$(data.description)[0].outerHTML: "<p style="color: red;">desc1</p>"

and it doesn't get changed. How to change it?

data.description has this value:

<p style="color: red;">desc1</p><p style="color: red;">desc2</p>

And I want only $(data.description)[0] changed.

Here is my whole code:

var ingsLines = $(data.description);
for (var i =0; i < ingsLines.length; i++) {
    if (someCondition) {
        $(data.description).eq(i).css('color', 'black');
    }
}
try{$('#myTextarea').html(data.description);}catch(err){}

And the code changes the value, it puts black instead of red, but data.description stays with red.

Upvotes: 3

Views: 3501

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382112

Use

$(data.description).replaceWith(function(){
    return this.outerHTML.replace('red', 'black')
});

Demonstration

If you want to change only first one, you may use this :

$(data.description).eq(0).replaceWith(function(){
    return this.outerHTML.replace('red', 'black')
});

Upvotes: 1

Ram
Ram

Reputation: 144669

If you want to change the color property of the first element, you can use css and eq methods:

$(data.description).eq(0).css('color', 'black');

Upvotes: 1

Related Questions