如何分离和预先将div分配给没有唯一ID的父div

问题描述 投票:0回答:1

使用分离和前置工作,将子元素从DIV(h4)中移动到它的父DIV(树中的两个DIV)。我所拥有的代码正在运行,但它会在页面上占用此DIV的每个实例,并将页面上的所有多个DIV添加到每个父DIV的顶部。

jQuery( function($){
$('.mp_m_blurb_1 h4.et_pb_module_header').detach().prependTo('.mp_m_blurb_1 .et_pb_blurb_content');
});

我意识到在具有相同ID /类的多个DIV元素的页面上,这将会发生。那么我如何告诉子元素移动到另一个父DIV但仅相对于其父元素而不必手动为每个元素添加唯一ID。

在某些页面上可能有10-15 +这些父DIV,我宁愿不必为每个DIV添加唯一ID,然后更新我的jQuery。

我希望能够使用单一课程。有更好的方法或方法吗?

试过这些资源,但他们没有帮助

Move a div somewhere else in the dom

How to move an element into another element?

Get class name using jQuery

jQuery: appendTo parent

https://www.elated.com/jquery-removing-replacing-moving-elements/

下面是有效的代码,但正如您所看到的,这将变得冗长乏味。 ;-)

jQuery( function($){
$('#mp_blurb_0 h4.et_pb_module_header').detach().prependTo('#mp_blurb_0 .et_pb_blurb_content');
$('#mp_blurb_1 h4.et_pb_module_header').detach().prependTo('#mp_blurb_1 .et_pb_blurb_content');
$('#mp_blurb_2 h4.et_pb_module_header').detach().prependTo('#mp_blurb_2 .et_pb_blurb_content');
$('#mp_blurb_3 h4.et_pb_module_header').detach().prependTo('#mp_blurb_3 .et_pb_blurb_content');
$('#mp_blurb_4 h4.et_pb_module_header').detach().prependTo('#mp_blurb_4 .et_pb_blurb_content');
$('#mp_blurb_5 h4.et_pb_module_header').detach().prependTo('#mp_blurb_5 .et_pb_blurb_content');
    });
jquery wordpress getelementsbyclassname prepend
1个回答
0
投票

你可以使用jQuery's .each()方法和attribute starts with选择器的组合。

使用$('[id^="mp_blurb_"]')将选择ID为mp_blurp_的所有元素。

$('[id^="mp_blurb_"]').each(function() {
    var $this = $(this);
    var $content = $this.find('.et_pb_blurb_content');
    $this.find('h4.et_pb_module_header').detach().prependTo( $content );
});

在这里查看我的工作示例:https://jsfiddle.net/z8of7qxp/

© www.soinside.com 2019 - 2024. All rights reserved.