开发者

jQuery .wrap() question

开发者 https://www.devze.com 2023-01-25 09:00 出处:网络
i\'m having some problems with jQuery $(document).ready(function() { var foo = $(\"<div><h1>Bar</h1><p>Hi</p><h1>Baz</h1><p>bye</p></div>\"

i'm having some problems with jQuery

$(document).ready(function() {
    var foo = $("<div><h1>Bar</h1><p>Hi</p><h1>Baz</h1><p>bye</p></div>");
    foo.filter("h1,h2").map(function(id) {
        $(this).wrap('<span color="red"/>');
    });
    alert(foo.html());
});

This code outputs

<h1>Bar开发者_Go百科</h1><p>Hi</p><h1>Baz</h2><p>bye</p>

The span's are nowhere to be seen. What am I doing wrong?


It doesn't have any effect because .filter() filters elements at that level, you could need .find() to get descendants like this:

$(document).ready(function() {
    var foo = $("<div><h1>Bar</h1><p>Hi</p><h1>Baz</h1><p>bye</p></div>");
    foo.find("h1,h2").wrap('<span color="red"/>');
    alert(foo.html());
});

You can test it out here. Also note you should use .each() instead of .map() for looping...but there's no need here, since you can just call .wrap() directly.


You don't want to use filter here, you want to use find. Also, why are you using map?

$(document).ready(function() {
  var foo = $("<div><h1>Bar</h1><p>Hi</p><h1>Baz</h2><p>bye</p></div>");
  foo.find("h1,h2").wrap('<span color="red"/>');
  alert(foo.html());
});

Live test


First off: your markup is invalid (Baz is wrapped by an opening h1 and a closing h2). But the .map reference says you need to return the value.

$(document).ready(function() {
    var foo = $("<div><h1>Bar</h1><p>Hi</p><h1>Baz</h1><p>bye</p></div>");
    var bar = foo.find("h1,h2").map(function(id) {
        return $(this).wrap('<span color="red"/>');
    });

});


You need .find() instead of .filter() since the heading elements are nested.

var foo = $("<div><h1>Bar</h1><p>Hi</p><h1>Baz</h1><p>bye</p></div>");

foo.find("h1,h2").wrap('<div color="red"/>');

Also, I changed it to wrap using a <div> instead of a <span> since I don't think it is valid to have a <span> wrapped around heading elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号