Skip to content Skip to sidebar Skip to footer

Help With Manipulating Child/parent Elements With Jquery

Currently I have this JQuery script var img = $(this); img.wrap('
'); img.parent().append('

' + img.attr('alt') + '

'); which

Solution 1:

I think the problem is your "if" statement, which should be:

if (img.parent('a').length) {
  // ...
}

Then, when you try to get the "href" of the <a> tag, you're calling "val()" and that's not necessary (or correct, even):

var targetLink =  img.parent('a').attr('href');

Also, though not relevant to your problem, the "alt" attribute is supposed to describe what the image is about, while the "title" is more like what I'd call a "caption". In other words, the "alt" text should be understandable to people who can't see the image at all, while the "title" describes an image to a person who can see it. Just a nit.;

Solution 2:

I would do it this way:

var img = $(this);
var target = $(img).parent();
if (target.is("a")) {
  target = target.parent();
}
target.wrap("<div>");
var div = target.parent();
div.addClass("photo");
$("<p>").attr("alt", $(img).attr("alt")).appendTo(div);

Some browsers are exceptionally slow at using innerHTML type methods for markup creation so I tend to favour the above approach, which uses diretc DOM element creation. To clarify, as of jQuery 1.4+ at least:

$("<pclass='photo'>...</p>')...

uses innerHTML but:

$("<p>").addClass("photo").text("...");

uses document.createElement().

Post a Comment for "Help With Manipulating Child/parent Elements With Jquery"