Search code examples
jquerywordpressgetelementsbyclassnameprepend

How to detach and prependTo a div to a parent div that does not have a unique ID


Working on moving a child element from within a DIV (h4) into it's parent DIV (two DIVs up the tree), using detach and prepend. The code I have is working but it takes every instance of this DIV on the page, and adds all the multiple DIV's on the page, to the top of every parent DIV.

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

I realize that on a page with multiple DIV elements of the same ID/class, this is what is going to happen. So how do I tell a child element to move to another parent DIV but only relative to its parent and without having to manually add a unique ID to each.

On some pages may have 10-15+ of these parent DIV's and I would prefer not to have to ad a unique ID to each one and then update my jQuery.

I would love to be able to use a single class. Is there a better way or approach?

Tried these resources but they did not help

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/

Below is the code that worked but as you can see, this is going to get long and tedious. ;-)

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');
    });

Solution

  • You could use a combination of jQuery's .each() method and the attribute starts with selector.

    Using $('[id^="mp_blurb_"]') will select all element with an ID starting with 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 );
    });
    

    See my working example here: https://jsfiddle.net/z8of7qxp/