Javascript change the souce of all images present inside a string - javascript

I have a message or string which contain both text as well as images as below.
var text = '<span class="user_message">hiiiiiii <img title=":benztip" src="path../files/stickers/1427956613.gif"> <img src="path../files/stickers/416397278.gif" title=":happy"></span>';
Before appending this to the the chat div i want to replace the src of the images to a default image.
How can i do that with Javascript or Jquery?

You can wrap your string into a jQuery-object and use the .find()-method to select the images inside the message-string:
var msg = '<span class="user_message">hiiiiiii<img title=":benztip" src="path../files/stickers/1427956613.gif" /><img src="path../files/stickers/416397278.gif" title=":happy" /></span>';
var $msg = $(msg);
$msg.find('img').attr('src', 'path_to_img');
$("#chat_content").append($msg);
Demo

Something like this in plain old JavaScript might work for you
// save string to temporary element
var tmp = document.createElement('div');
tmp.innerHTML = '<span class="user_message">hiiiiiii <img title=":benztip" src="path../files/stickers/1427956613.gif"> <img src="path../files/stickers/416397278.gif" title=":happy"></span>';
// loop through images
var imgs = tmp.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
var src = imgs[i].getAttribute("src"); // get current src
src = "http://placehold.it/100x100"; // do something with path
imgs[i].setAttribute("src", src); // set it
}
// output or whatever
document.writeln(tmp.innerHTML);

Try this for javascript solution, will work in older browsers too.
var spanNode = document.getElementById("spanId");
spanNode.getElementsByTagName("img")[0].src = "Src1";
spanNode.getElementsByTagName("img")[1].src = "Src2";
You can also use For loop for tagnames if there are more than 2 images.

document.getElementById("image_id").src="default_img_name";

Related

How can I store list of image and video files in JavaScript?

I want to store list of images and video files store in list in java script. I used formData.append() method, to store files with key. It is stored properly.
But in between I am not able to delete the file using key from formData.
So I need another solution for this problem.
Code:
var file = $("#pictureUrl")[0].files[0];
formdata.append(index + "p", file);
var vfile = $("#videofile")[0].files[0];
formdata.append(index + "v", vfile);
Delete Code :
var key=id+"v";
formdata.delete(key);
Use Arrays As Containers:
var imgDiv = document.querySelector('.imagesDiv');
var vidDiv = document.querySelector('.videosDiv');
var images = ['image_path/1.jpg','image_path/2.jpg','image_path/3.jpg','image_path/4.jpg'];
var videos = ['video_path/1.mp4','video_path/2.mp4','video_path/3.mp4','video_path/4.mp4'];
// Append Images to a div with class="imagesDiv"
var addedImg = '';
function addImages() {
for (i=0; i<images.length; i++) {
addedImg+= '<img src="+images[i]+" alt="Alternative Text" >';
}
imgDiv.insertAdjacentHTML('beforeend', addedimg);
}
// Append videos to a div with class="videosDiv"
var addedVid = '';
function addVideos() {
for (j=0; j<videos.length; j++) {
addedVid+= '<video width="320" height="240" controls><source src="+videos[j]+"
type="video/mp4"></video>';
}
addedVid.insertAdjacentHTML('beforeend', addedVid);
}
addImages();
addVideos();
i know this is old, if you are facing same issue use
fd.append(media[${i}],data[i].media) if it is a list of object do fd.append(media[${i}][image],data[i].image); fd.append(media[${i}][video], data[i].video);
please surround the key with backticks (this)==> `
.I cant use it here since that is the same for code snippet on stack overflow

how to place a array[i] items in <img src=""> and <a href=""> tags

i have an retrieved array items in the var test,
for example :
var test = img;
Where test[0] holds the value that is grabbed from database as /images/gallery/1.jpp
Now i need to place the var test[0] to be place within img src="" and a href="", so how can i achieve this?
Assign a value to the property "id" of your img and play with its attributes.
<img src="" id="image_id_here" width="300" height="400">
<script>document.getElementById('image_id_here').setAttribute('src', test[0]);</script>
Assumptions made:
"test" is an array of strings
You demand working through a client-sided scripting language such as Javascript to perform front-end operations.
you need a div tag with the id of container:
<div id="container"></div>
You can then use javascript to iterate over the list:
var imgs = "";
for (var i = 0; i < test.length; i++) {
var img = document.createElement('img');
img.setAttribute('src', test[i]);
imgs += img.outerHTML;
}
var container = document.getElementById('container');
container.innerHTML = imgs;
See plunker

trying to dynamically replace the url from "a href" but javascript is not updating results

I'm trying to replace the urls in the html using javascript but it is not working although when I test it by I "alerting" them the values pop up correctly, but when I publish it and click on the images the new urls are not applied. Any help would be greatly appreciated
Could you please look at the code and tell me what is going on?:
<script>
var rutaBase = "assets/fotos/";
function cambieFotos(cualFoto) {
var listaFotos = ["360.jpg", "foto3.jpg", "mathura.jpg"];
var numFotosLista = listaFotos.length;
var foto1 = document.getElementById("foto1");
var foto2 = document.getElementById("foto2");
var foto3 = document.getElementById("foto3");
for (i = 0; i < 3; i++) {
var fotoAleatoria = listaFotos[Math.floor(Math.random() * numFotosLista)];
var fotoRoll = document.getElementById("foto" + (i + 1));
fotoRoll.src = "assets/fotos/" + fotoAleatoria;
fotoRoll.href = "assets/fotos/" + fotoAleatoria; //this code is not working.
var sacarFotoLista = listaFotos.indexOf(fotoAleatoria);
listaFotos.splice(sacarFotoLista, 1);
numFotosLista = listaFotos.length;
}
}
</script>
<div id="contenedor">
<img id="foto1" onMouseOver="cambieFotos(this)" src="assets/fotos/360.jpg"> <--!this needs to update-->
<img id="foto2" onMouseOver="cambieFotos(this)" src="assets/fotos/foto3.JPG"><--!this needs to update-->
<img id="foto3" onMouseOver="cambieFotos(this)" src="assets/fotos/mathura.jpg"><--!this needs to update-->
</div>
<!--contenedor-->
fotoRoll is an <img>, not the surrounding <a>. You should modify the parent instead:
fotoRoll.parentNode.href="assets/fotos/"+fotoAleatoria;
You're setting the href on the image element, not the hyperlink element. Try something like
fotoRoll.parentNode.href="assets/fotos/"+fotoAleatoria;

Writing HTML to new window opened issue

I have this code:
<div class="col3">
<a id = "training-launch-button" href="javascript:void(0);" title=" My title here" class="button" onClick="Test();">Launch</a>
</div>
function Test() {
var new_window= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
new_window.document.createElement("div");
document.getElementsByTagName('div')[0].innerHTML = '<ol><li>html data</li></ol>';
}
something is not right, I dont see the ordered list item?
I eventually want to build some HTML in the new window.
Use this Js
function Test() {
var newWindow= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var newContent = "<HTML><HEAD><TITLE>One Sub Window</TITLE></HEAD>";
newContent += "<BODY><div><ol><li>html data</li></ol></div>";
newContent += "</BODY></HTML>";
newWindow.document.write(newContent);
newWindow.document.close();
}
I think this is your problem; getElementsByName returns an array, not one element, so;
new_window.document.getElementsByTagName('div')[0].innerHTML = '<ol><li>html data</li></ol>';
NB: I have a '[0]' in there
I would try
new_window.document.getElementsByTagName('div')[0].innerHTML = ...
This should do it:
var new_window= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var div = new_window.document.createElement('div');
new_window.document.body.appendChild(div);
div.innerHTML = '<ol><li>html data</li></ol>';
You are actually not appending the new div to the new document's body, you'll have to use .appendChild() method for that, see this :
function Test() {
var new_window = window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var div = new_window.document.createElement("div");
new_window.document.getElementsByTagName('body')[0].appendChild(div);
div.innerHTML = '<ol><li>html data</li></ol>';
}
see here - working example

javascript extract html block from string

I have a string extracted from a div and stored in variable "str". I now need to extract the ... subset of it.
str = '<div id="xyz"><p>This is a paragraph</p><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></div>';
Thanks in advance for any help with this.
You could try something like the below:
var a = $(str).find('a').html();
make it innerHTML of a temporary div.
use getElementsByTagName("A") to retreive all "A" nodes.
get their HTML .
Here is a running example : http://jsfiddle.net/3fZch/
var str = '<div id="xyz"><p>This is a paragraph</p><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></div>';
var newElem = returnTheParentNode(str);
var anchors = newElem.getElementsByTagName('A');
/* anchors has all the a tags of the html string */
for(var i = 0 ; i < anchors.length ; i++)
{
var aHTML = getHTML(anchors[i]);
alert(aHTML);
}
function returnTheParentNode(htmlStr)
{
var myCont = document.createElement('DIV'); // create a div element
myCont.innerHTML = htmlStr; // create its children with the string
return myCont; // return the parent div
}
function getHTML(theNode)
{
var myCont = document.createElement('DIV');
myCont.insertBefore(theNode,null);
return myCont.innerHTML ;
}
The expression you need is:
str.match(/a href="([^"]*)"/)[1]
But this assumes there is only one a tag in your string and you used double quotes to delimit the href.
Made a jsfiddle: http://jsfiddle.net/eDAuv/
Why not extract the link BEFORE you store it in a string?
myLink = $(".myDiv a").html()
This could work:
var link = $(str).find("a").get(0).outerHTML;
alert(link);

Categories

Resources