Sun_Blood
Sun_Blood

Reputation: 335

Can I use addClass on information stored in an HTML string?

I have a string that for example looks like this.

var html = '<div class="templatemo_post_text grid-85">
<div id="wmd-preview"><h2>Skriv något!</h2>
<p>Lorem ipsum</p></div>
<div class="templatemo_post_footer">
<div class="templatemo_post_on">
<span class="orange">Skrivet den</span> 3 Mar 2013</div>
<div class="templatemo_post_comment">
<a href="#">Inlägg nummer </a>
</div></div></div>';

Can I use the .addClass() in some way to add a class to the id=wmd-preview?
Actually my question goes for all javascripting to modify existing variables. One other thing I would like to do is to replace the whole tag with a new one.

Thanks.

Upvotes: 2

Views: 4043

Answers (3)

Sun_Blood
Sun_Blood

Reputation: 335

Thanks for the comments but it didn't solve my problem and the reason for that is bad input from me. I was getting the html by using innerHTML and that didn't work well with the solutions.

I am leaving my code here for anyone that needs it. The code is a way of getting my DIV and when the ajax get a success it will change the and delete the id wmd-preview.

mydiv = document.createElement('div')
mydiv.className = 'templatemo_post_area addbottom grid-parent';
mydiv.innerHTML = document.getElementById('preview').innerHTML;
$.ajax({
    type: "POST",
    dataType: 'json',
    url: "/pages/posts_ajax.php",
    data: {
        data : text,
        time : timepost
    },
    success: function(response) {
        $(mydiv).find('#wmd-preview').removeAttr('id');
        $(mydiv).find('#postnr').text('Inlägg nummer '+response.id);
        $(mydiv).insertAfter('div#post_area');
    }
});

Upvotes: 1

Drew Noakes
Drew Noakes

Reputation: 310852

You can turn that HTML into a DOM element:

var element = $(html);

Then select the div you want:

var div = element.find('#wmd-preview');

Then add the class:

div.addClass('new-class');

EDIT

To turn your modified DOM elements back into an HTML string, you can use jQuery's html function:

html = element.html();

Note that this gives the inner HTML of the element, so the enclosing div is missing. You can get around this by adding it to another div.

html = $('<div></div>').append(element).html();

Upvotes: 5

Hussein Nazzal
Hussein Nazzal

Reputation: 2557

here is what you want to do

var html = '<div class="templatemo_post_text grid-85"><div id="wmd-preview"><h2>Skriv något!</h2><p>Lorem ipsum</p></div><div class="templatemo_post_footer"><div class="templatemo_post_on"><span class="orange">Skrivet den</span> 3 Mar 2013</div><div class="templatemo_post_comment"><a href="#">Inlägg nummer </a></div></div></div>';

$(html).find('.orange').addClass('someclass')

Upvotes: 0

Related Questions