I want to use jQuery to determine if a link is a text link or an image link. If it’s a text link, I want to grab the text. If it’s an image link, I want to get the id of the image. I tried using .text() for the text links, but this also returns true for my image links.
function get_link_content(object) {
if($(object).text()) {
var link_content = $(object).text();
}
// even if it's an image link, this ^^ always returns true
else if($(object).find('img')) {
if($(object).find('img').attr('id')) {
var link_content = $(object).find('img').attr('id');
}
else {
var link_content = 'unidentified';
}
}
return link_content;
}
By text link, I mean:
<a href="#">This is a text link</a>
By image link, I mean:
<a href="#"><img id="the-id" src="#"></a>
Is there another method I should be using besides .text()?
Below is a cleaned up and slightly optimized version of your code:
Edit: Here’s a further optimized version (with a jQuery element passed).
As you can see, I’ve removed the
id, since it’s to be stored in thelink_contentanyway (if theidexisted and had a value). This means that it will be slightly faster when it encounters an image that has anid, since it doesn’t have to assign the id value to the variableidand then assignidtolink_elementin a second step if there was a value. It’s also a bit shorter than the first version, which increases readability a little bit.