Changing image src depending on which word is in the element - javascript

I want to change the image displayed depending on which word is in the element, which will change frequently. I have tried using the indexOf method, to try and seach for the keyword which will decide whether to show a specific image in element 1 or element 2, but without luck.
<div class="main>
<h1 id="nextGame" onLoad="nextGames()">Aug 25, 2019: Home against Genoa</h1>
<p id="homeTeam"><img src="" id="teamHome"> vs <img src="" id="teamAway"></p>
</div>
<script>
var nextGame1 = document.getElementById("nextGame").indexOf("Home");
if (nextGame1 !== -1); {
document.getElementById("homeTeam").src = "asroma2.png";
} else {
document.getElementById("teamAway").src = "asroma2.png";
}
</script>
I expected my code to be able to see if the element "nextGame" had the string "Home" in it. If so, the image source of "homeTeam" would be changed to my specified src, and if not "teamAway" would be assigned the src.
This was clearly not the case.
Does anyone know what I did wrong?

Using document.getElementById("nextGame") will result in complete HTML Tag instead of the text present in the tag. You can use document.getElementById("nextGame").innerText to get the text inside the tags and then you can use the indexOf operator to identify if "Home" is present in it or not. The complete code will be written as follows:
<div class="main>
<h1 id="nextGame" onLoad="nextGames()">Aug 25, 2019: Home against Genoa</h1>
<p id="homeTeam"><img src="" id="teamHome"> vs <img src="" id="teamAway"></p>
</div>
<script>
var nextGame1 = document.getElementById("nextGame").innerText.indexOf("Home");
if (nextGame1 !== -1) {
document.getElementById("homeTeam").src = "asroma2.png";
} else {
document.getElementById("teamAway").src = "asroma2.png";
}
</script>
You have also closed the if statement with a semicolon and also used an additional closing bracket at the end, both of which will throw a syntax error.

I think you want to use something like
var nextGame1 = document.getElementById("nextGame").innerText.indexOf("Home");

Related

How can I define addEventListener('click' with an ancestoral node hierarchy

Introductory note:
It was suggested the question below was not clearly stated. I simply wish to define an addEventListener('click' trap that traverses three nodes. One of the two examples I present below runs through a (grand)parent id ('id="ArticleStyle"' in the article tag) -> traverses down node to its child 'h1' -> and then further down node to the h1 spawned child, 'a'. Which is, the 'a href' being clicked and listened for.
I have two js scripts properly working that serve my needs by luck alone; not by robust planning. Both I would like to contain and evaluate in a grandparent node/wrapper using that unique id as the defined starting point. It would be essential in the second script to do so since there would be over a hundred (and growing) unique ids needed; if it weren't for the fact I am succeeding by using 'h1'-'a'. Fortunately here, 'h1' is not yet used elsewhere.
The 'a' links in the first script (immediately below / and one of its two HTML blocks is included below that) are fortunately parented by just a total of four unique id allowing it to be functional without the attempted EVALUATION for HANDLING line commented out. Otherwise, if I used an 'a'-'img' (as I used 'hi'-'a' in the second script), there would be sucked in traffic on clicks to other page navigation icons based on their similar 'a'-'img' coding. I would hope to use the attempted line of code I commented out, code it correctly and have it create a container/wrapper/node representing a lineage of 'div class="flagLinkVIEW"'-'a'-'img' || 'div class="flagLinkVIEW"'-'a'-'span' as a filter where none else enter in.
<script>
//Toggles between Montage and Montage_VIEW based on, clicking the img icon.png or the span text below it
document.addEventListener('click', ({ target }) => {
//!!!!!!!!!!!!!!!! FIX 'IF' LINE COMMENTED OUT in second line below this !!!!!!!!!!!!!!!!!!!!!!!!
//Code incorrectly formatted in line under this comment
//if ((target.matches('.flagLinkVIEW a > img')) || (target.matches('.flagLinkVIEW a > span'))) {
if (target.parentElement.id === "VIEW_topIconOnOff0") {
sessionStorage.displayStateMontage = "idMontage_VIEW";
document.body.style.background = "white";
}
if (target.parentElement.id === "VIEW_topIconOnOff1") {
sessionStorage.displayStateMontage = "idMontage";
document.body.style.background = "rgb(225, 213, 191)";
}
if (target.parentElement.id === "VIEW_btmIconOnOff0") {
sessionStorage.displayStateMontage = "idMontage_VIEW";
document.body.style.background = "white";
}
if (target.parentElement.id === "VIEW_btmIconOnOff1") {
sessionStorage.displayStateMontage = "idMontage";
document.body.style.background = "rgb(225, 213, 191)";
}
//}
//!!!!!!!!!!!Above is the closing bracket of the FIX 'IF' LINE COMMENTED OUT !!!!!!!!!!!!!!!!
});
</script>
<div id="Icons-midNAV" class="IconOpacityControl-p5 LNKiconCOLORS">
<a href="#" onclick="window.open ('./Poetry%20-%20Montage%20of%20the%20Years_files/PDF%20-%20MASTER%20Montage%20of%20the%20Years.pdf', 'PDF Master',
'resizable=yes,scrollbars=yes,top=100,left=260,height=420,width=420'); return false;">
<img class="PDF-IconBC-Pv" src="./b-pdf_w.png" alt="PDF Master" />
<span class="BtmCtrIconTextStyle PDF-TextBC-Pv">MASTER</span></a>
<div class="flagLinkVIEW">
<!-- Instead of class, which would be nice, I could if must, use a unique id of
flagLinkVIEW_A here if necessary, and elsewhere in the second similar block, an
id of flagLinkVIEW_B. It would be instructive though, to solve with a class example. -->
<a id="VIEW_btmIconOnOff0" href="./Poetry%20-%20Montage%20of%20the%20Years.html">
<img class="VIEW-IconBC-pV" src="./binoculars-detail-2A.png" alt="Basic-VIEW" />
<span class="BtmCtrIconTextStyle VIEW-TextBC-pV">BasicVIEW</span></a>
<a id="VIEW_btmIconOnOff1" href="./Poetry%20-%20Montage%20of%20the%20Years.html">
<img class="VIEW-IconBC-pV" src="./binoculars-detail-2A.png" alt="Basic-VIEW" />
<span class="BtmCtrIconTextStyle VIEW-TextBC-pV">FullVIEW</span></a>
</div>
</div>
The solution I seek for the second script I believe is similar. Here I would wish use the unique id attached to the article node. I would hope to incorporate the incorrectly coded line now commented out, and fix it to contain a specified node lineage of 'article id="ArticleStyle"'-'h1'-'a' and use it as a filter where none else enter in. Again, the js script is immediately below with the HTML following it.
<script>
//Sets localStorage to transfer present sessionStorage to a new _blank tab/window being opened
document.addEventListener('click', ({ target }) => {
//!!!!!!!!!!!!!!! Change line below to a correctly syntaxed lineage of:
//if ((target.matches('#ArticleStyle h1 > a')) !!!!!!!!!!!!!!!!!!
if (target.matches('h1 a')) {
localStorage.previousMenu = sessionStorage.previousMenu;
localStorage.motherMenu = sessionStorage.motherMenu;
localStorage.rootMenu = sessionStorage.rootMenu;
}
});
</script>
<article id="ArticleStyle">
<h1 style="line-height:0; padding-top:1.8em">
<a href="./Poetry%20-%20Black%20Holes%20and%20When%20Time%20Stands%20Still.html" target="_blank">
Black Holes and When Time Stands Still</a></h1>
<!--multiple 'h1' child nodes, as above but with differing URLs -->
</article
<script>
//Sets localStorage to transfer present sessionStorage to a new _blank tab/window being opened
document.addEventListener('click', ({ target }) => {
//!!!!!!!!!!!!Change line below to: if ((target.matches('.ArticleStyle h1 > a'))
if (target.closest('.ArticleStyle h1 > a')) {
localStorage.previousMenu = sessionStorage.previousMenu;
localStorage.motherMenu = sessionStorage.motherMenu;
localStorage.rootMenu = sessionStorage.rootMenu;
}
});
</script>
Maybe your are looking for this https://developer.mozilla.org/en-US/docs/Web/API/Element/closest still i would try to have classes or ids on my layout and put different handlers instead of in body

javascript if class x contains z get link of class y

i'm no js expert but need to execute some js in my applescript. Don't know if this is possible as the html page contains several instances of this div class.
If nested div class ".product_card__title" contains "my search term"
Extract href link from nested class ".js-search-product-link"
From main div with the class ".product_card"
A ANLTERNATIVE VERSION TO THE ONE ACCEPTED HERE IN THIS THREAD.
My Html:
<div class="product_card powersearch__product_card">
<a href="/shop/XYZ" class="js-search-product-link">
<div class="product_card__image" style="background-image:url(https://image.jpg);"></div>
<div class="product_card__title">SEARCH FOR THIS TITLE</div>
<div class="product_card__meta">€14</div></a></div>
What i have so far is:
tell application "Safari"
open location "https://teespring.com/search?q=rocker"
delay 5
set theLinks to (do JavaScript "Array.prototype.slice.call(document.querySelectorAll('.product_card')).map(function(d,i){var title = d.querySelector('.product_card__title'),link = d.querySelector('a');if(title && link && /Rocker/gi.test(title.textContent)){return link.href}})")
end tell
return theLinks
Replace yourSearchTerm with whatever you want to search below:
Array.prototype.slice.call(document.querySelectorAll(".product_card"))
.map(function(d,i){
var title = d.querySelector(".product_card__title"),
link = d.querySelector("a");
if(title && link && /yourSerchTerm/gi.test(title.textContent)){
return link.href
}
})
For all your divs with class of "product_card" it will return an array containing the hrefs, for the ones it could find, otherwise undefined
FIDDLE:
https://jsfiddle.net/ibowankenobi/gc6r2h3v/1/
As apple returns the last global value it might help to change the part where you set the theLinks variable:
set theLinks to (do JavaScript "someGlobal = Array.prototype.slice.call(document.querySelectorAll('.product_card')).map(function(d,i){var title = d.querySelector('.product_card__title'),link = d.querySelector('a');if(title && link && /Rocker/gi.test(title.textContent)){return link.href}})")

Change only one character of all img src of a class using javascript

I want to change the src of all the images which are in the 'car-image' class.
But I do not have to change whole url. I just want to change one character.
I want edit this -
<div class="car-image">
<img src="/cars/3_large_1.png">
</div>
To this-
<div class="car-image">
<img src="/cars/3_large_2.png">
</div>
And this format is common in all the image in this class.
I tried something like this-
var allsrc = document.getElementsByClassName('car-image');
allsrc[0].src="/cars/3_large_2.png";
This is not working.
How can i do this in javascript?
you are setting src of wrong node allsrc returns your div not the image.
Try this
allsrc[0].childNodes[1].setAttribute("src","/cars/3_large_2.png")
A more elegant solution would be to use replace function with regex. If you know the image src pattern and similar changes apply to all image src, you can build a regex. In that case, instead of changing each image src one by one, you can iterate over the elements that contains car-image class and find out the first childNode and change the src attr.
// find all elements that contains class car-image
var carImgDivs = document.getElementsByClassName('car-image');
// iterate over carImgDivs and execute an imediate function to just pass the
// childNode1 that is the image. Use replace function with regex to find out the
// changed image src value and set the changed src value to childNode1
for(var i = 0; i < carImgDivs.length; i++) (function(childNode1) {
if(childNode1) {
var replacedSrc = childNode1.getAttribute('src').replace(/(_)(\d)/, "$12");
childNode1.setAttribute("src", replacedSrc);
}
})(carImgDivs[i].childNodes[1]);
For a image src like /cars/3_large_1.png, the regular expression (_)(\d) matches a underscore that follows a digit and captures both. The $1 in replace string "$12" says to keep the first capture group(underscore) as it is and 2 says to replace the second capture group(a digit) with 2. Basically, the regex matches with _1 in the above image src. _ is the first capture group and 1 is the second capture group. So, in the end, the image src gets changed to /cars/3_large_2.png
I want to change the src of all the images which are in the
'car-image' class using javascript.
You can change <img> src for all car-image classes like this:
var all = document.getElementsByClassName('car-image');
for(var i = 0; i < all.length; i++){
var image = document.getElementsByClassName('car-image')[i].getElementsByTagName('img');
image[0].setAttribute("src", "/cars/3_large_2.png");
}
<div class="car-image">
<img src="/cars/3_large_1.png">
</div>
<div class="car-image">
<img src="/cars/5_large_1.png">
</div>
<div class="car-image">
<img src="/cars/7_large_1.png">
</div>
<div class="car-image">
<img src="/cars/9_large_1.png">
</div>
(Inspect elements and see new src's)
If you include jquery in your page you can do
$(".car-image img").attr("src", "/cars/3_large_2.png");
Use(jQuery solution) : $( "img:nth-child(1)" ).attr('src', <new_name>);
The nth-child(i) means ith image.
Example:
$(".car_image img:nth-child(1)").attr('src', '/cars/3_large_2.png');
To change all the images just remove the :nth-child()
What about this
var x = document.getElementsByClassName('car-image')[0];
var img = x.getElementsByTagName('img')[0];
img.src = "/cars/3_large_2.png";

Using jQuery to detect if element has a certain style attribute

I'm writing a script to detect whether or not an image is present on a webpage. It's a standard formatting with their html for this section. If there is not an image it looks like
<div id="photo" style="display: none;">
<img id="image" src="IMAGESOURCE" onerror="img2txt()" alt="">
</div>
if there is an image present that same html looks like this
<div id="photo">
<img id="image" src="IMAGESOURCE" onerror="img2txt()" alt="">
</div>
Right now in the script I'm using this, which doesn't work (or i wouldn't be here :D )
var images = ($('#photo[style*="display: none"]').length === 0 ? false : true);
if (images) {
$('#yes[value="Yes"]').click();
}
else {
$('#no[value="No"]').click();
}
(The clicks are for the radio buttons on the form that I am filling out based on this image query)
As of right now the if/else statement is giving the radio "No" a click on a page where it should be a yes. I've tried using
if (!images) {
$('#yes[value="Yes"]').click();
}
else {
$('#no[value="No"]').click();
}
just to see if my boolean was incorrect. But with that adjustment it just does the opposite again. Any help is much appreciated. Thanks
So it is always display:none when not present? jQuery has a specific selector for that :visible.
var present = $("#photo").is(":visible");
To find out whether the image is visible or not:
$('#image:visible').length;
With reference to your own posted code, you could use:
var imageVisible = $('#image:visible').length,
toClick = imageVisible ? 'yes' : 'no';
$('#' + toClick + '[value=' + toClick + ']').click();
Or, avoiding the unnecessary attribute-selectors (given that an id is a unique identifier:
$('#' + toClick).click();
References:
:visible.

What is the easiest way to check if string contains any image tag?

For example I have text:
"testestestestt testestestes <img src='image.jpg'>"
I want to write function which check if in string is img tag and return true
using regex:
"testestestestt testestestes <img src='image.jpg'>".match(/<img/)
var str = "testestestestt testestestes <img src='image.jpg'>";
var hasImg = !!$('<div />').html(str).find('img').length
Obviously, regular expressions are not recommend for parsing HTML, however, depending on the way you are using this, you may want to be assured that the img tag(s) have a corresponding ending tag. This is a slightly more robust regular expression for that:
if("<img>TestString</img>".match(/<img[^<]*>[\w\d]*<\/img>|<img[^\/]*\/>/i))
{
alert('matched');
}
else
alert('nope');
Matched Test Cases:
- blahsdkfajsldkfj<img blah src=\"\">iImmage123dfasdfsa</img>
- blahsdkfajsldkfj<img>iImmage123dfasdfsa</img>asdfas
- <img src=\"\"></img>
- <img></img>
- <img />
Unmatched Test Cases:
- <img (other regex would match this)
- <img>
Once you match it you can easily process it with an XML or HTML parser are then check if it has the src attribute etc.
Actually, given answers are fast, but they may face some special cases which mispredict img tags e.g. I posted my <picture> in <imgur>
`I posted my <picture> in <imgur>`.match(/<img/)
// ["<img", index: 25, ...]
also, there is a faster version of '<img' keyword search in a strings duo to this answer in modern browsers.
"testestestestt <img src='image.jpg'>".indexOf('<img') > -1
But the most reliable method is either you use a full img tag regex-matcher or let the browsers do things they've already done.
const hasImage = htmlString => {
var div = document.createElement('div');
div.innerHTML = htmlString
return Boolean(div.querySelector('img'));
}
// tests
hasImage("testestestestt <img src='image.jpg'/>")
// true
hasImage("testestestestt <img src='image.jpg/>")
// false
hasImage("I posted my <picture> in <imgur>")
// false
hasImage function is highly inspired by this answer

Categories