2

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.

4

3 回答 3

5

您可以将该 HTML 转换为 DOM 元素:

var element = $(html);

然后选择你想要的div:

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

然后添加类:

div.addClass('new-class');

编辑

要将修改后的 DOM 元素转换回 HTML 字符串,可以使用jQuery 的 html 函数

html = element.html();

请注意,这给出了元素的内部 HTML,因此缺少封闭的 div。您可以通过将其添加到另一个 div 来解决此问题。

html = $('<div></div>').append(element).html();
于 2013-03-03T13:57:02.847 回答
1

感谢您的评论,但它并没有解决我的问题,原因是我输入错误。我是通过使用 innerHTML 来获取 html 的,但它不适用于解决方案。

我将我的代码留给任何需要它的人。该代码是获取我的 DIV 的一种方式,当 ajax 成功时,它将更改并删除 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');
    }
});
于 2013-03-06T20:02:21.580 回答
0

这是你想要做的

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')
于 2013-03-03T13:59:17.660 回答