【问题标题】:How to detach and prependTo a div to a parent div that does not have a unique ID如何将 div 分离并添加到没有唯一 ID 的父 div
【发布时间】:2019-04-13 22:33:41
【问题描述】:

使用分离和前置将子元素从 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,但仅相对于其父 DIV,而无需手动为每个元素添加唯一 ID。

在某些页面上可能有 10-15+ 个这些父 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】:

    您可以结合使用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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      相关资源
      最近更新 更多