Changing an attribute by providing a second one - javascript

I have:
var cnt = '
<img alt="pic1" src="/data/18139/1.jpg" />
<div>
<p>
<img alt="pic2" id="zwei" src="/data/18139/2.jpg" />
</p>
<img alt="pic3" src="/data/18139/3.jpg" />
</div>';
I want to get/set the alt attribute of an img tag by giving the src attribute, no matter how deep the img is.
I tried:
$(cnt).find("img[src$='"+pic+"']").attr('alt'); //can only get the object
$(cnt).filter("img[src$='"+pic+"']").attr('alt') //can only get the alt on the root of thre DOM.
Also tried some combinations and .find(function(... but I simply can´t work it out.
The special thing is, I can not work directly in the DOM. My HTML is stored in the cnt variable. So I´m calling a function like this:
function refreshEditorAlt(src,newalt){
var cnt=getEditorContent();
var newcnt = cnt.replace($("img[src$='"+src+"']", cnt).attr('alt'), newalt);
setEditorContent(newcnt);
}

You can try this code, note that jQuery methods can help you much:
var cnt = '<img alt="pic1" src="/data/18139/1.jpg" /><div><p><img alt="pic2" id="zwei" src="/data/18139/2.jpg" /></p><img alt="pic3" src="/data/18139/3.jpg" /></div>';
var $cnt = $("<div>" + cnt + "</div>");
//input
var src = "/data/18139/1.jpg";
var newAlt = "Xpic";
//update new alt
$cnt.find("img[src$='" + src + "']").attr('alt', newAlt);
//output
cnt = $cnt.html();
$('#out').text(cnt);
Demo.
Note that you should wrap the cnt into some element (such as a <div></div>) so that you can use jQuery to solve your problem.

Try this to get the value:
$(cnt).find("img[src$='"+pic+"']").attr('alt');
Try this to set the value:
$(cnt).find("img[src$='"+pic+"']").attr('alt', newValue);

I think your problem is with the line breaks where you've defined the variable cnt. So instead you want:
var cnt = '<img alt="pic1" src="/data/18139/1.jpg" /><div><p><img alt="pic2" id="zwei" src="/data/18139/2.jpg" /></p><img alt="pic3" src="/data/18139/3.jpg" /></div>';
And then something like this will work:
alert($(cnt).find("img[src$='/data/18139/2.jpg']").attr('alt'));
Obviously you're wanting to pass the value of src into a function or something, but hopefully this should solve your problem.
Quick demo to show it works this way http://jsfiddle.net/4z5Sh/

Related

How to concatenate Javascript variable in HTML image source tag

How do you concatenate a Javascript variable into the url of a HTML image source tag? I have tried .$ANSWER. "$ANSWER" and +$ANSWER+ and none of these are working.
Do I need to use getElementbyID?
I have a folder of images named cat.jpg, dog.jpg, etc and I have a javascript array of these animal names.
One of them is chosen as $ANSWER and I want to then display the image, using the variable $ANSWER.
I have scoured the internet for any example of how to do this but can't find any.
What I have below is my best guess of how to write it, but I get "Not found" in the console log. The picture are in the folder, as this was working in PHP before I rewrote this in Javascript.
<div>
<img id="ANSWER" src='pictures/animals/$ANSWER.jpg' width=80% height=auto >
</div>
<script>
document.getElementById("ANSWER").src='pictures/animals/$ANSWER.jpg';
</script>
Also, if there is an easy way to do this in JQuery, I would love to know.
This is easy enough to do with raw JavaScript; simply ensure that each of the 'string' components are wrapped in quotes, and then make use of the plus sign (+) to concatenate with your variable(s). Note that the variable(s) should not be in quotes; only the supporting string(s) should be.
For example, if you have the variable cat, and want to craft it in the the URL pictures/animals/cat.jpg, you would use 'pictures/animals/' + $ANSWER + '.jpg'.
Also note that your width and height values need to be wrapped in quotes as well, and the initial setting of src is irrelevant, as it is overwritten.
This can be seen in the following:
var $ANSWER = 'cat';
document.getElementById("ANSWER").src = 'pictures/animals/' + $ANSWER + '.jpg';
console.log(document.getElementById('ANSWER').src);
<div>
<img id="ANSWER" width="80%" height="auto">
</div>
For a jQuery-specific solution, you can use the attr() method, passing 'src' as the first parameter, and your combined URL as the second:
var $ANSWER = 'cat';
$("#ANSWER").attr('src', 'pictures/animals/' + $ANSWER + '.jpg');
console.log(document.getElementById('ANSWER').src);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img id="ANSWER" width="80%" height="auto">
</div>
Hope this helps! :)
If $ANSWER is declared in PHP, the rendered HTML/JS won't know about it.
You'd need to do something like this:
<div>
<img id="ANSWER" src='pictures/animals/$ANSWER.jpg' width=80% height=auto >
</div>
<script>
document.getElementById("ANSWER").src='pictures/animals/<?php echo $ANSWER; ?>.jpg';
</script>
Note: I haven't used PHP in ages, so I may be wrong in the specifics of the PHP syntax. Hopefully, you'll get the idea, though.
If it's declared somewhere in the JS, you can concatenate it like some of the other answers here suggested:
<div>
<img id="ANSWER" src='pictures/animals/$ANSWER.jpg' width=80% height=auto >
</div>
<script>
document.getElementById("ANSWER").src='pictures/animals/' + $ANSWER + '.jpg';
</script>
Is this what you are looking for:
var el = document.getElementById("ANSWER");
var images = ['dog', 'cat', 'fish'];
var index = 0;
function setImage() {
var img = images[index];
el.src = `pictures/animals/${img}.jpg`;
index++;
if (index >= images.len) {
index = 0;
}
}
setImage(); // Get the first URL into the img tag
setInterval(setImage, 2000); // Change images every 2 seconds.
<div>
<img id="ANSWER" src="" width="80%" height="auto" />
</div>
Here it is with images online:
var el = document.getElementById("ANSWER");
var images = [
'https://cdn.rentcafe.com/dmslivecafe/UploadedImages/57ffbe5a-055d-43c1-98fa-8be16ba066ca.jpg',
'http://archer.gamebanana.com/img/ico/sprays/kitten2_render.png',
'https://is5-ssl.mzstatic.com/image/thumb/Purple118/v4/71/46/8d/71468d8f-f9f9-cc04-b346-04a8fef0e7f1/source/256x256bb.jpg'];
var index = 0;
function setImage() {
el.src = images[index];
index++;
if (index >= images.len) {
index = 0;
}
}
setImage(); // Get the first URL into the img tag
setInterval(setImage, 2000); // Change images every 2 seconds.
<div>
<img id="ANSWER" src="" width="80%" height="auto" />
</div>

How to find an element in HTML string and change an attribute using jQuery

This seems to be a very simple question but I've been at it for a couple of hours trying to make it work.
I have a string like:
var myhtml = '<div id="wrapper"><div id="full" width="800px"></div></div>';
I need to find my div #full, remove it's "*width*" attribute and then use myhtml with the updated version.
I'm using this in jQuery:
var newhtml = $(myhtml).filter("#full").removeAttr("width");
console.log(newhtml );
Expecting this: <div id="wrapper"><div id="full"></div></div>
But it returns "<div id="full"></div>" and not the whole variable.
Use .find("#full") to select the element then remove attribute. The original object retains the value.
var myhtml = $('<div id="wrapper"><div id="full" width="800px"></div></div>');
var newhtml = myhtml.find("#full").removeAttr("width");
console.log($(myhtml)[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

How to access the Javascript variable value outside the script tag

I want to access the Javascript variable value outside the Javascript tag.
function getprices(input) {
return input.match(/[0-9]+/g);
}
var subtotals = get_getprices('%GLOBAL_OrderTotal%');
var Grand_total = subtotals[0];
<img height="0" width="0" border="0" src="http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=I want the Grand+Total Value here">
You'd need to update the src property on that img element. Let's suppose you gave the img an id (you don't have to, there are other ways to select it, but I'm keeping it simple):
<img id="the-image" height="0" width="0" border="0" src="http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=I want the Grand+Total Value here">
Then:
function getprices(input) {
return input.match(/[0-9]+/g);
}
var subtotals = getprices('%%GLOBAL_OrderTotal%%'); // <=== Changed to `getprices`, was `get_getprices`
var Grand_total=subtotals[0];
var img = document.getElementById("the-image");
img.src = "http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=" + Grand_total;
It looks like Grand_total will always be a number, but for the general case where it might not be, , be sure to use encodeURIComponent (it doesn't do any harm even if it is a number):
img.src = "http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=" + encodeURIComponent(Grand_total);
If you didn't use an id on the img, that's fine, you can use any CSS selector via document.querySelector. That's supported by all modern browsers, and also IE8.
Note that there are other issues with that code, though, not least that getprices looks fairly suspect.
All you need to do is to assign your value to src of img in your javascript
$("#imgNeeded").attr("src",".../"+Globalvalue)
As T.J. Crowder said. make sure you encode URI if your variable contain something other than number
You can use
document.getElementsByTagName("img")[***index of the image tag***].src = "<THE STRING>"+<THE VARIABLE>+"<THE REMAINING STRING>";
or assign an id to the <img> and use
`document.getElementById("id of the image").src = ""++"";
The problem the provided approaches share is, that how they are, your image will get loaded with the unwanted source before changed:
<html>
<head>
<script>
function getprices(input){return input.match(/[0-9]+/g)};
function changeSrc(){
var tE = document.querySelector("img[src*='saleAmount=']");
var tS = getprices('anyPrice1');
if (tE && tS) tE.src += encodeURIComponent(tS[0]);
};
</script>
</head>
<body onload = 'changeSrc()'>
<img height = '0' width = '0' border = '0' src = 'http://JUSTTOSHOWtesting.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=' onerror = 'console.log(this.src)'>
</body>
Your console will log two calls:
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount= net::ERR_NAME_NOT_RESOLVED
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=1 net::ERR_NAME_NOT_RESOLVED
So what you could do is placing a placeholder, until you have the source you need:
<html>
<head>
<script>
function getprices(input){return input.match(/[0-9]+/g)};
function createSrc(){
var tE = document.querySelector("ins[src*='saleAmount=']");
var tS = getprices('anyPrice1');
if (tE && tS){
var tI = document.getElementById('iPlaceholder');
if (!tI){
tI = document.createElement('img');
tI.id = 'iPlaceholder';
tI.onerror = function(){console.log(this.src)};
tE.parentNode.insertBefore(tI, tE.nextSibling);
};
tI.src = tE.getAttribute('src') + encodeURIComponent(tS[0]);
};
};
</script>
</head>
<body onload = 'createSrc()'>
<ins src = 'http://JUSTTOSHOWtesting.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount='></ins>
</body>
</html>
Now your console will merely log one call:
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=1 net::ERR_NAME_NOT_RESOLVED

add javascript variable in image url

My Random Number Generate code is
var randomnumber=Math.floor(Math.random()*99999)
Now I want to put this variable output in a image scr url..
Here is my url
<img src="http://www.myexample.com/get/image.php?vcid=14851&t=481" alt="" id="imge"/>
So what will my code?
<img src="http://www.myexample.com/get/image.php?vcid='+ randomnumber +'&t=481" alt="" id="imge"/>
??
Please help me
In pure Javascript you could do it like
var randomNumber = 1;
var image = document.getElementById("imageId");
var imageSrc = image.getAttribute("src");
image.setAttribute("src", imageSrc + randomNumber);
To put your number at the correct place you could use some string split functions, but since the order of query strings don't matter you should just put your vcid query at the end.
Try adding this in your <script>:
document.getElementById("imge").src = "http://www.myexample.com/get/image.php?vcid=" + randomnumber + "&t=481";
I'd personally suggest:
var img = document.getElementById('imge');
img.src = img.src.replace(/vcid=(\d+)/, function(){
return randomnumber=Math.floor(Math.random()*99999);
});
// purely to see the src has been changed, this is *not* relevant or required
img.title = img.src;
<img src="http://www.myexample.com/get/image.php?vcid=14851&t=481" alt="" id="imge"/>
References:
JavaScript Regular Expressions.
String.replace().

Get multiple elements same class - JavaScript (getElementsByClass)

I have an 'a href' that is a title.
Vendor1 product title
I want to display an image based on the first word of the title.
Vendor1 product title
<div class="logo"></div>
Vendor2 product title
<div class="logo"></div>
Vendor3 product title
<div class="logo"></div>
These are item cells and they use the same template to be generated so the classes are always the same. There are many of them.
The script I have so far is working but only for the first product in the list (shows correct logo).
function getlogo() {
var string1 = document.getElementsByClassName('title')[0].innerHTML;
var vendor = string1.replace(/([a-z]+) .* ([a-z]+)/i, "$1").toLowerCase();
document.getElementsByClassName('logo')[0].innerHTML = '<img src="/myimages/' + vendor + '.jpg" width="100px" height="50px" onerror="imgError(this);">';
function imgError(image) {
image.onerror = "";
image.src = "default.jpg";
return true;
}
}
getlogo();
I've looked around but sure how to loop this or even if that is the solution.
http://jsfiddle.net/W7bm5/
It's easy if you use jQuery each function.
function imgError(image) {
image.onerror = "";
image.src = "default.jpg";
return true;
}
$(document).ready(function() {
$(".title").each(function() {
var string1 = $(this).text();
var vendor = string1.replace(/([a-z]+) .* ([a-z]+)/i, "$1").toLowerCase();
$(this).html('<img src="/myimages/' + vendor + '.jpg" width="100px" height="50px" onerror="imgError(this);">');
});
});
or you can do it with the pure javascript, but put your logics in a loop, with [0] replaced to the loop index.
Update - here's how to keep the current text links:
function imgError(image) {
image.onerror = "";
image.src = "default.jpg";
return true;
}
$(document).ready(function() {
$(".title").each(function() {
var string1 = $(this).text();
var vendor = string1.replace(/([a-z]+) .* ([a-z]+)/i, "$1").toLowerCase();
var html = $(this).parent().html();
$(this).parent().html(html + '<br /><img src="/myimages/' + vendor + '.jpg" width="100px" height="50px" onerror="imgError(this);">');
});
});
You could use a for loop to run through the code you have for a different index of the getElementsByClassName results. See your jsFiddle
You could also ditch the getElementByClassName, which I think has spotty support in some browsers and isn't especially good performance, and navigate the DOM using JavaScript if your structure is always the same, or even jQuery if you'd like a library to make it easier.
But by far the best is if you did it when it was generated in the first place. How are you generating the code and could you not use that to achieve what you are trying to achieve?

Categories