替换子元素,保留父元素

5
我想问一个关于以下内容的问题: 如何用其他元素替换子元素并保留父元素应用于文档。 我尝试使用replaceWith()函数,但没有解决我的问题。 以下是我的代码:
template_gallery = '<div class="mahbub-modal">'+
        '<button type="button" class="mahbub-btn-close">'+elmahbub.btn_close+'</button>'+
        '<div class="mahbub-modal-gallery">'+
        '<div class="mahbub-gallery-content">'+
        '<div class="mahbub-column-left">'+
        '<img src="'+elmahbub.source+'" class="mahbub-image" alt="'+elmahbub.alt_image+'">'+
        '<div class="mahbub-btn-more">'+
        '<button type="button" class="mahbub-more-left" title="'+elmahbub.title_prev_button+'">&#10094;</button>'+
        '<button type="button" class="mahbub-more-center" title="'+elmahbub.title_center_button+'">'+elmahbub.icon_btn_center+'</button>'+
        '<button type="button" class="mahbub-more-right" title="'+elmahbub.title_next_button+'">&#10095;</button>'+
        '</div>'+
        '<div class="mahbub-gallery-footprint">'+elmahbub.title+
        '<p class="mahbub-gallery-footprint-subtitle">'+elmahbub.sub_title+'</p>'+
        '</div>'+
        '</div>'+
        '<div class="mahbub-column-right">'+elmahbub.content+
        '</div>'+
        '</div>'+
        '</div>';

Jquery :

if (elmahbub.type == 'video') {
        video_element = '<video width="100%" height="500px" controls>'+
        '<source src="'+elmahbub.source+'" type="video/ogg">'+
        '<source src="'+elmahbub.source+'" type="video/mpeg">'+
        elmahbub.error_load+'</video>';
        if (elmahbub.gallery[0].enabled == false) {
            template_gallery = $(template_gallery).children($('.mahbub-image')).replaceWith(video_element);
            modal = template_gallery;
        }
        else{

        }
    }

我希望模板库中有一个视频元素 :-) 谢谢。
1个回答

10

只需使用jQuery来确定目标父元素,然后使用html函数添加子元素。

$('#parent-div').html("<h1>test</h1>");

如果您想替换现有的DOM元素,只需执行以下操作...
$('#parent-div').html($('#divIWant'));

我的问题是如何用其他元素替换,兄弟。因为我的template_gallery也将应用html()函数。 - user8455694

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接