简体   繁体   中英

Wrap each element and then prepend a new div to the wrapper?

I'm trying to use jQuery (3.1.1) to wrap elements of a given class and then prepend a new div as the first element inside the wrapper. I've tried a number of things and this is as close as I can get.

testWrap = function() {
    var testWrapImpl = function(index, value) {
        var div = $("<div></div>");
        $(value).wrap(div);
        $(div).prepend("<div class='child-div'>some text</div>");   
        alert("done");
    };
$(".myClass").each(testWrapImpl);

This code successfully wraps each element with the outer div but doesn't seem to do anything with the "some text" div.

The alert does show up for each of the elements in the page and the page seems to load with out error.

What am I doing wrong?

The .wrap() method wraps a copy of the wrapper around each target element. Thus once you've called .wrap() , your div thing is a perfectly OK element but it's not the actual wrapper.

What you could do is add a class to the wrapper, do the wrapping, then find the wrappers and add the extra element:

$(".myClass")
    .wrap("<div class='wrapper'></div>")
    .closest(".wrapper")
    .prepend("<div class='child-div'>some text</div>");

There's no real need to do your own .each() iteration; the jQuery routines will do that implicitly. If you need to make decisions about the wrapper for each element in "myClass", you can pass a function to .wrap() . The function will be called for each individual element with a single argument containing the index into the list, and with this bound to the element for that iteration. Your code in the function can inspect the element or do whatever, and the return value from the function will be used as the wrapper. So for example to give a numbered class to each wrapper:

$(".myClass")
    .wrap(function(index) {
      return "<div class='wrapper wrapper-" + index + "'></div>";
    })
    .closest(".wrapper")
    .prepend("<div class='child-div'>some text</div>");

You can .prepend() before using .wrap() to achieve what you're after.

Also, once you've defined div variable as a jQuery object, you should reference div variable rather than $(div) .

    var testWrapImpl = function(index, value) {
        $(value).wrap( '<div></div>' ).parent().prepend("<div class='child-div'>some text</div>");   
        alert("done");
    };
$(".myClass").each(testWrapImpl);

https://jsfiddle.net/2966pxqz/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM