Javascript to get and change element Title - javascript

I want to change images inside a div when a link is clicked. I did that, but I can't retrieve the TITLE of the image from the TITLE of the link.
JavaScript
function changeImage(element) {
document.getElementById('imageReplace').src = element;
}
HTML 1
my link
HTML 2
<img src="pics/empty.png" id="imageReplace"/>
When I click the link shown in HTML1, the image changes where the HTML2 code is, but the "title" attribute is not retrieved and nothing pops up when the mouse is over the new pic. I want to retrieve this title attribute.
Can anyone help?

Modify your function a little:
function changeImage(src, a) {
var img = document.getElementById('imageReplace');
img.src = src;
img.title = a.title;
}
and HTML:
my link
So you basically pass HTMLAnchorElement object (a tag) into changeImage function where you can use its properties like title. There you set image title equal to link one.

Link:
my link
Image:
<img src="pics/empty.png" id="imageReplace"/>
Function:
var changeImage = function(element) {
document.getElementById('imageReplace').src = element;
document.getElementById('imageReplace').title = this.title;
return false;
}
Fucntion.prototype.call()
The call() method calls a function with a given this value and arguments provided individually.

use this
function changeImage(element) {
var element_title =element.title;
var element_src=element.src;
document.getElementById('imageReplace').src = element_src;
document.getElementById('imageReplace').title= element_title ;
}
</script>
my link
<img src="pics/empty.png" id="imageReplace"/>

Since you tagged this as jQuery, you can use that to set title of any element like this,
To get title attribute value = $("#elem").attr("title");
To set title = $("#elem).attr("title","title-value");
Assumption - there is an element with id = elem.
In your case you need to get title in onclick. To achieve this, you can do it like this.
onclick="return changeImage('pics/1.jpg',this);"
function changeImage(imgsrc,element) {
$("#imageReplace").attr("src",imgsrc);
var title = $(this).attr("title");
$("#imageReplace").attr("title",title);
return false;
}

Related

Removing a created function in JavaScript

I have written this code by using some basics. I simply wanted to remove the image that I have created by using the function Generate() by a button. I have written the following code to remove the image generated. Please help me.
Please note that I have linked my button with the function Reset1(). Can someone give me the code to do the following please.
function Generate()
{
var image=document.createElement('img');
var div=document.getElementById('flex-box-gen');
image.src="https://thecatapi.com/api/images/get?format=src&type=gif&size=small"
div.appendChild(image);
}
function Reset1()
{
document.getElementById('Generate').remove();
}
You could either assign an id to your image element and use that to remove in your second function:
function generate() {
var image=document.createElement("img");
image.id = "image-01";
...
}
function reset() {
var image = document.getElementById("image-01");
var parent = image.parentNode;
parent.removeChild(image);
}
Or if there is nothing else in your containing div element you could just empty all elements from it:
function reset() {
document.getElementById("flex-box-gen").innerHTML = "";
}
getElementById will query a DOM element, not a javascript element.
What you can do, supposing you have only one img in your flex-box-gen is:
var imgs = document.querySelectorAll('#flex-box-gen img')
if(imgs.length > 0){
imgs[0].remove();
}
With a null-check in case the image was already removed
image.setAttribute('id',"Generate");
Add this line in generate function.

Using class instead of id in JS to do an action

First, sorry I'm not good with javascript.
HTML:
<div id="Comment-ID">
<p class="comment-content">...</p>
</div>
The javascript: (Edit: Added the whole code)
<script type='text/javascript'>
function autoloadmore() {
var loadmoreClass = document.getElementsByClassName("loadmore")[0];
var loadmoreChild = loadmoreClass.querySelector('a')
if (loadmoreClass) {
loadmoreChild.click();
}
}
//<![CDATA[
function InsertarImagenVideo(id) {
var IDelemento = document.getElementById(id),
sustituir = IDelemento.innerHTML;
sustituir = sustituir.replace(/\[img\](.[^\]]*)\[\/img\]/ig, "<img class='img-comentarios' src='$1'\/>");
document.getElementById(id).innerHTML = sustituir;
}
//]]>
window.onload = function() {
autoloadmore();
setTimeout(function(){
InsertarImagenVideo('Comment-ID');
},3000);
};
</script>
"InsertarImagenVideo" replaces some text inside with an image. Instead of using it on "Comment-ID", I want to use it on "Comment-class".
Note: I can't edit the HTML.
I couldn't find anything when I searched, or maybe I didn't know how to look. Can someone help me with this?
You can use document.querySelector to select an element by class:
Update this line:
var IDelemento = document.getElementById(id),
to var IDelemento = document.querySelector(id),
and pass the class selector to your method InsertarImagenVideo
setTimeout(function(){
InsertarImagenVideo('.comment-content');
},3000);
I found a simple way to insert an image into the <p class="comment-content">...</p> element by grabbing the parent <div id="Comment-ID">.
I'm assuming that you need to grab the unique id to then access the inner <p> element to replace the existing text with an image. This code grabs the unique id element, then grabs the first <p> tag using .getElementsByTagName('p')[0]. One thing I did add is a proper image load script to update the <p> tag with the image once it has been loaded (maybe this removes the need for that setTimeout function you have?).
let classElement = document.getElementById("Comment-ID").getElementsByTagName('p')[0];
let imageObject = new Image();
imageObject.src = `https://www.clipartmax.com/png/full/1-14442_smiley-face-png-smiley-png.png`;
imageObject.onload = function() {
classElement.innerHTML = `<img id="myImg" src="${imageObject.src}" />`;
let imageElement = document.getElementById(`myImg`);
imageElement.width = 100;
imageElement.height = 100;
};
Here's a JSFiddle demo of the upper code in action.
Hope this helps :)

change image of img tag using innerhtml

i want to change image using innerhtml of img tag when i click on it my code is given below
tempData +='<td >';
tempData +='<img src="'+frontImg+'" id='+ii+' onClick="flipImage(this.id);" />';//from where flipImage call
tempData +='</td>';
it works fine but it change image when it return form the function but i wanted to change it before flipImage return
function flipImage(m)
{
var jsonLen = jsonImages.images.length;
var imgNumber = finalImageArray[m];
for(jsn = 0;jsn <jsonLen ;jsn++)
{
if(jsonImages.images[jsn].imageKey== imgNumber)
{
realImage = jsonImages.images[jsn].imagePath;
var element = document.getElementById(m);
// var mg = '<img src="bool.jpg" />'; // change when this line execute what should i put here.?
//element.innerHTML=mg; want like this.
//this is actual code but it change image after returning the function so i don't want this.
element.innerHTML=realImage;
element.setAttribute('src',realImage);
element.setAttribute('onclick', '');
break;
}
}
}
so i wanted to change image before flipImage return.
this is just a sample code and
You can't use innerHTML for <img /> tags as they don't have HTML inside them, they're singletons and have no inside contents.
Just use imgElement.setAttribute('src', 'http://...'); to change the image.

changing/stripping off url pointed by image using javascript

Might be a very simple javascript injection question, but say I have an image html tag:
<img src="rainbow.gif">
I wanted to perform a javascript, such that when clicked on the image, it doesn't go to the myfile.htm. In other words, I wanted to strip the a href which surrounds the img. How can I do this in javascript? Say that I have the following to reference the image tag:
document.elementFromPoint(%f, %f)
f can be replaced by any double/float value
If you have a reference to the img element, then its parent (parentNode) will be the link (in the structure you've given). Three options:
Remove the link entirely
Disable the link
Change the link's href
1. Remove the link entirely
You can remove the link entirely by doing this:
var link = img.parentNode,
linkParent = link.parentNode;
linkParent.insertBefore(img, link);
linkParent.removeChild(link);
That uses parentNode to find the parent and grandparent, insertBefore to move the image, and removeChild to remove the link. Note that this assumes the image is the only thing in the link.
2. Disable the link
If you want to keep the link but render it useless, you can do this:
var link = img.parentNode;
if (link.addEventListener) {
link.addEventListener("click", function(event) {
event.preventDefault();
}, false);
}
else if (link.attachEvent) {
link.attachEvent("onclick", function() {
return false;
});
}
else {
link.onclick = function() {
return false;
}
}
3. Change the href of the link:
This is trivial, just set the href property of the link element (which you can get because it's the parent node of the image) to whatever you want:
img.parentNode.href = /* ...something else */;
For instance:
img.parentNode.href = "http://stackoverflow.com";
...would change the link to point to Stack Overflow.
Live example
Some references:
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Application APIs
<a id="anchorWithImage" href="myfile.htm"><img src="rainbow.gif"></a>
Why not grab the anchor, then set its href to nothing:
var a = document.getElementById("anchorWithImage");
a.href = "javascript:void(0)";
Or grab it and set its click event to cancel the default action, which is to browse to the location of its href property
a.onclick = function(e) {
e.preventDefault();
}
Or do you want to grab all anchors that have an image as their child element, and strip out their href?
jQuery would make this easy, if that's an option for you
$("a").filter(function() {
return $(this).children("a").length === 1;
}).attr("href", "javascript:void(0)");
or
$("a").filter(function() {
return $(this).children("a").length === 1;
}).click(function() { return false; }); //returning false from jQuery handlers
//prevents the default action
EDIT
If you were to have a reference to the image, and wanted to set its parent's anchor's href, you'd grab it with the parentNode property:
var img = document.getElementById("imgId");
var a = img.parentNode;
a.href = "javascript:void(0)";
With jQuery you could use something similar to this
$("a").has("img").click(function(e).preventDefaults();});
Basically all this line does is identifies all tags within the document containing an tag disables standard event process
From your comment on another answer, it sounds like you actually want to change/eliminate the target of links at a specific position in the page. You could do something like this:
var el = document.elementFromPoint(10, 10);
while(el) {
if(el.nodeName.toLowerCase() == 'a')
el.href = 'javascript:';
el = el.parentElement;
}
This would loop up from the selected element, identify if the element is an anchor, and set the href to something that does nothing.
you can change the href of a tag on window load itself, so you need not worry when it is clicked.
window.onload = fundtion(){
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
var parentElem = imgs[i].parentNode;
if(parentElem.tagName === 'A')
parentElem.setAttribute("href", "javascript:void(0)");
}
};

find <img> tag inside text string

I have an xml document (from a feed), which I'm extracting values from:
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = $(this).find("description").text();
Now inside "description" i need to get the img element, but this is causing me some problems. "descripttion" is a regular string element and it seems i can't call the ".find()" method on this, so what do i do?
I have tried calling .find():
var img = $(this).find("description").find("img");
But it's a no go. The img is wrapped in a span, but I can't get to this either. Any suggestions? I'd prefer to avoid substrings and regex solutions, but I'm at a loss.
I've also tried turning the "description" string into an xml object like so:
var parser = new DOMParser();
var desc = parser.parseFromString(test,'text/xml');
$(desc).find("img").each(function() {
alert("something here");
});
But that doesn't work either. It seems like it would, but I get a "document not well formed" error.
Try enclosing the contents of the description tag in a dummy div, that seemed to work better for me, and allowed jQuery's .find() to work as expected.
e.g.
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = '<div>' + $(this).find("description").text() + '</div>';
var image = $(description).find('img');
Hi and thanks for the prompt replies. I gave GregL the tick, as I'm sure his solution would have worked, as the principle is the same as what I ended up with. My solution looks like this:
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = $(this).find("description").text();
var thumbnail = "";
var temp_container = $("<div></div>");
temp_container.html(description);
thumbnail = temp_container.find("img:first").attr("src");
So wrap the string in a div, and then use "find()" to get the first img element. I now have the image source, which can be used as needed.
maybe you should try to convert the description text to html tag and then try to traverse it via jquery
$('<div/>').html($(this).find("description").text()).find('img')
note: not tested

Categories