I'm trying to dynamically and a link to an image, however I cannot correctly determine is the parent link already exists.
This is what I have,
if (element.parent('a'.length) > 0)
{
element.parent('a').attr('href', link);
}
else
{
element.wrap('<a></a>');
element.parent('a').attr('href', link);
}
Where element refers to my img element and link refers to the url to use.
Every time the code runs, the else clause is performed, regardless of whether or not the img tag is wrapped in an a tag.
Can anyone see what I'm doing wrong?
Any advice appreciated.
Thanks.
In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.
The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.
jQuery parent() Method The parent() method returns the direct parent element of the selected element.
The first line should be:
if (element.parent('a').length > 0)
Assuming element
is actually a jQuery object:
if (!element.parent().is("a")) {
element.wrap("<a>")
}
element.parent().attr("href", link);
If element
is a DOM node:
if (!$(element).parent().is("a")) {
$(element).wrap("<a>")
}
$(element).parent().attr("href", link);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With