Can't seem to grab alt attribute - javascript

I'm trying to grab the "alt" attribute of an image inside "uCW", but nothing's printing.
Here's the image:
<img class="i09qtzwb n7fi1qx3 datstx6m pmk7jnqg j9ispegn kr520xx4 k4urcfbm bixrwtb6" height="261" src="https://external-ort2-2.xx.fbcdn.net/safe_image.php?d=AQAayZaQwp_d10l4&w=750&h=391&url=https%3A%2F%2Fimg.buzzfeed.com%2Fbuzzfeed-static%2Fstatic%2F2020-04%2F28%2F13%2Fasset%2F36517ba3257e%2Fsub-buzz-279-1588079535-1.png%3Fcrop%3D768%3A402%3B0%2C8&cfs=1&ext=jpg&_nc_hash=AQBIX7qpH_aPKJby" width="500" alt="A Reporter Went On "GMA" Wearing No Pants. He Didn't Realize We Could All See.">
(Sorry about the long line, I couldn't figure out how to get it to wrap.)
Here's my code:
var title = $(uCW).find('[src^="https://external"]').attr("alt");
console.log(title);
Nearly identical code works fine for grabbing the URL:
var image = $(uCW).find('[src^="https://external"]').attr("src");
console.log(image);

Related

trying to grab image url within div's children

I'm making an extension that grabs an image URL within the "uCW" div on an HTML page.
Currently, I have:
var uCW = jNode.closest("div._q7o");
var image = uCW[0].children[1].getElementsByTagName("img")[0].src;
console.log(image);
That finds the image by going into the div/children and pulling the image. Unfortunately, this method is problematic, since it stops working if the children change, which they regularly do.
Instead, I want to select the image by searching the div and all its children (there are a lot of them) for the first image/string that starts with "https://external" (all the images I want start this way, and that doesn't seem to change.)
This is what I tried:
var uCW = jNode.closest("div._q7o");
var image = $(uCW).find([name^="https://external"]).src;
console.log(image);
This doesn't work. The console just prints "undefined."
You could do it like this, if ucw is a classname (if it's an id, you would write $("#ucw") instead):
var image = $(".ucw").find('[src^="https://external"]').attr("src");
console.log(image);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ucw">
<img src="https://external/1.jpg"/>
</div>
If your images have a name attribute with the source of the image as value, you can also adjust your attempt to fetch the images via their name attribute like you did:
var image = $(".ucw").find('[name^="https://external"]').attr("src");

how to display dynamic <img src> on webpage

i want to make a website that allow users to input questions, and then the website will display some pictures related to user input
i tried to wrap the output in img src tag, however the output is simply a line of code instead of picture
<img src="path/reply.jpg" width="68" height="90" alt="reply">
how can i tell the website to recognize it as a picture and display it ?
is it possible to extend this function to embed youtube video etc. ?
==================================================================
Added some scripts below, i guess this is the code that limiting output as text only.....
function createRow(text) {
var $row = $('<li class="list-group-item"></li>');
$row.text(text);
$chatlog.append($row);
}
Update: i amended $row.text(text); to $row.html(text); , it can properly display html code now.
you can use ParentNode.append() function to append new image element to your html. (documentation here: https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append)
Example:
var yourImage = document.createElement("img");
yourImage.src = "some/dynamic/source.jpg"
document.body.append(yourImage);
It is very simple, just try the following changes:
Add id attribute to your img tag:
<img src="path/reply.jpg" width="68" height="90" alt="reply" id="img1">
And in Jquery:
$(document).ready(function ()
{
$("#img1").attr({ "src": "img.jpg" });
});

Using this.title to retrieve an image title

I apologize if this seems to be a stupid or overly simple question, but I have been given an assignment that tasks us with changing the TITLE of an image using an OnClick handler. Thus far, I've been able to change the title of the image, but the assignment also requires us to utilize this.title in order to access the original title of the image.
I've tried quite a lot thus far, and have only come back with "undefined" as the title. Here is my code copy and pasted below. I would really appreciate any help!
This is what I used to try to get the original title of the image:
<img id="image" src="https://bb9.canyons.edu/bbcswebdav/pid-692768-dt-content-rid-9288981_1/courses/2015SU-CMPSCI190-16424/tick.gif" alt="tick" onclick="getValue()" />
<script>
function getValue() {
var x = document.getElementById('image').title;
alert(x.innerHTML)
}
</script>
And this is what I want to use to try to change the title of the image:
<img src ="https://bb9.canyons.edu/bbcswebdav/pid-692768-dt-content-rid-9288981_1/courses/2015SU-CMPSCI190-16424/tick.gif" title="insert original image title here" onclick="this.title='My New Title';"/>
I think that your code is quite correct, the only problem is that you are trying to call innerHTML on a string (the title). Maybe try something like:
function setValue() {
document.getElementById('image').title = "NEW TITLE";
}
if you want to change the value or just
function getValue() {
var x = document.getElementById('image').title;
alert(x);
}
to show the title value

Replacing source of an image with Jquery

Im building an app with Phonegap. It takes xml from an rss feed and creates html from it to present a news feed. The problem is the image paths are relative. I need to replace the relative path with the full path. The images tags appear inside a "description" xml tag. I get the contents of description like this:
$(xml).find('item').each(function (index) {
description = $(this).find('description').text();
console.log('description');
The console output is:
<p>Senior Rugby</p>
<p>CBC v CBS</p>
<p>
<span class="mjwideimg"><img width="300" height="247" src="/images/latestnews2/Resized/logo_300x247.jpg" alt="logo" />
</span>
</p>
I then try to replace path with a full path. I do:
$(description).find('img:first').attr('src', 'http://www.domain.com/img/test.png');
And then get the new html with full path:
description = $(description).html();
console.log(description);
However, this is just outputting:
Senior Rugby
with everything else stripped away. What am I doing wrong?
In first console.log you are doing
description = $(this).find('description').text();
console.log('description');
here you are log the xml node not the variable you coded.
And in another, you did something different (this time you did it for variable)
description = $(description).html();
console.log(description);
Another point is use .prop() instead of .attr()
$(description).find('img:first').prop('src', 'http://www.domain.com/img/test.png');
When you are finding the image, is description still set to $(this).find('description').text();?
If so the JQuery object is not pointing to HTML element but rather a string of text that is within that element.
Try replacing description with $(this).find('description');
In the end I did this:
description = $(this).find('description').text();
$(description).find('img').each(function(i, obj){
src = $(obj).attr('src');
//check if not full path
if(src.indexOf('http') === -1){
//therefore its a relative path
description = description.replace(src,"http://domain.com"+src);
}
});

How to add alternate text to pictures displayed by clicking on buttons?

Is there a way to add separate alternate text (such as "picture 1/2 not available") in case a picture fails to display? How can I change this code to allow that to happen?
(Sridhar's code)
<script type = "text/javascript">
function pic1()
{
document.getElementById("img").src = "picture 1 source";
}
function pic2()
{
document.getElementById("img").src ="picture 2 source";
}
</script>
<img src = "" id = "img"/> <input type="button" value="Show Picture
1" onclick="pic1()"/> <input type="button" value="Show Picture 2"
onclick="pic2()"/>
Is there a way to add separate alternate text (such as "picture 1/2
not available") in case a picture fails to display?
Yes, that is what the alt attribute is for - it is actually a required attribute for images anyway.
You can just set the alt tag of an image using .alt like so:
var image = document.getElementById("img");
image.src = "Image src here"
image.alt = "Image alt here - if image failed to render, you will see this!"
Assuming you have to do it by JavaScript. Most people simply just include it in the HTML itself:
<img src = "" id = "img" alt="Alternative text here!"/>
See more about the alt attribute here.
Edit: You could look into using onerror in regard to Derek's point:
"onerror allows for different alt text when an image is simply not found
rendered or when the image is not found"
Yes, there is a way. Use the onerror attribute with the error text or a path to an alternate image.
<img onerror="this.src='/path/to/alternate/img.jpg'" src="/your/img.jpg">
or
<img onerror="this.alt='picture 1/2 not available'" src="/your/img.jpg">
Edit: Of course, you should be using the (required) alt attribute on every image, as Zenith points out. Use of onerror assumes you wanted to show the user something different if the image could not be found instead of, say, the user is using a screen reader or has otherwise chosen to disable images. One alternative is to show the original alt text with the 'not available' message appended:
<img alt="picture 1/2" onerror="this.alt=this.alt+': not available'" src="/your/img.jpg">
Demo

Categories