This question already has answers here:
Get immediate first child element
(1 answer)
How to add/update an attribute to an HTML element using JavaScript?
(4 answers)
Closed 6 years ago.
How to target the img element in JavaScript to change img src.
<body>
<div class="cover">
<img src="img.jpg" width="60" height="60">
</div>
</body>
document.querySelector(".cover img").src = "/test/test.jpg";
please visit HTML DOM querySelector() Method for more information (compatibility, ...)
element.querySelector('img') can get you there as well.
var cover = document.getElementsByClassName('cover')[0],
img = cover.querySelector('img');
img.src = 'http://placehold.it/60x60';
<div class="cover">
<img src="img.jpg" width="60" height="60">
</div>
First select you parent class and then using that select your child element.
var a = document.querySelector(".cover");
var b = a.querySelector("img");
b.style.width = "500px";
b.style.height = "500px";
b.src = "https://source.unsplash.com/category/nature";
If you do not want to support legacy browsers you can do with with document.querySelector:
document.querySelector(".cover img").setAttribute("src", "anotherimage.png");
Related
This question already has answers here:
Can multiple different HTML elements have the same ID if they're different elements?
(17 answers)
Closed 2 years ago.
In this code when I use [i] it does not work but if I use [0] or [1] instead of [i] it works.
I do not understand why [i] is not working with src.
HTML code
<div class="player">
<p >Player 1
</p>
<img id="myimg" src="images/dice6.png">
</div>
<div class="player">
<p> Player 2
</p>
<img id="myimg" src="images/dice6.png">
</div>
JS code
var images = ["images/dice1.png","images/dice2.png","images/dice3.png","images/dice4.png","images/dice5.png","images/dice6.png"];
for (var i = 0; i < document.querySelectorAll("#myimg").length; i++){
document.querySelectorAll("#myimg")[i].addEventListener("click", changeImg);
function changeImg(){
var randomNumber1 = Math.floor(Math.random() * images.length);
document.querySelectorAll("#myimg")[i].src = images[randomNumber1] ;
}
}
Don't use ID's double they had to be unique. Better use classes instead.
Edited Version
In the eventListener call a function for your changeImg. There get the random Image and use `this`to get the actual element and change the source.
Note: Because random in JS is not really random I added to search as long random as the image is the same like actual. Otherwise you had sometimes to click multiple for a change.
For testing it's better to see if you use the full_page link (in the upper right corner of the output window).
var images = ["https://media.flaticon.com/dist/min/img/home/kiranshastry.png","https://www.pokewiki.de/images/thumb/d/d5/Sugimori_848.png/250px-Sugimori_848.png","https://assets.pokemon.com/assets/cms2/img/pokedex/full/034.png","https://assets.pokemon.com/assets/cms2/img/pokedex/full/030.png"];
for (let i = 0; i < document.querySelectorAll(".myimg").length; i++){
document.querySelectorAll(".myimg")[i].addEventListener("click", changeImg);
}
function changeImg(){
let randomNumber1;
do {
randomNumber1 = Math.floor(Math.random() * images.length);
} while (this.src == images[randomNumber1]);
this.src = images[randomNumber1] ;
}
<div class="player">
<p >Player 1</p>
<img class="myimg" src="https://www.pokewiki.de/images/thumb/d/d5/Sugimori_848.png/250px-Sugimori_848.png">
</div>
<div class="player">
<p> Player 2</p>
<img class="myimg" src="https://assets.pokemon.com/assets/cms2/img/pokedex/full/034.png">
</div>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
<a href="http://example.com">
<p>select this text</p>
<img src="" alt="">
</a>
Need to be able to copy text from p tag. The problem that p and img inside a and I can't select it.
I need exactly this HTML structure, as user should be able to copy link from that block. How can I do that?
If you're asking for a solution in pure javascript, I'm guessing that this can work ?
var els = document.querySelectorAll("a[href='http://example.com']");
console.log(els[0].textContent);
Could be simpler using jQuery
This is'nt correct use block-level elements as children of inline elements.
in your case,use of jQuery like this:
var copyStr = $('a[href="http://example.com"] > p').text();
Using textcontent property
const a = document.querySelector('a');
console.log(a.textContent);
<a href="http://example.com">
<p>...</p>
<img src="" />
</a>
Simply define an id to p tag and pull the text inside p tag using id like following:
$(document).ready(function(){
var par = $('#pid').text();
console.log(par)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<a href="http://example.com">
<p id="pid">...</p>
<img src="" />
</a>
You can do so using Javascript execCommand("copy") see this explained in comment:
function CopyText() {
/* Select Text inside p tag using createTextRange() */
if (document.selection) { // IE
var range = document.body.createTextRange();
range.moveToElementText(document.querySelector('#copytext p'));
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.querySelector('#copytext p'));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
/* Copie the Text inside the input to Clipboard */
document.execCommand("copy");
/* Alert success */
alert("Url Copied to Clipboard")
}
img {
width: 100%
}http://example.com
<a href="javascript:void(0)" id="copytext" onclick="CopyText()">
<p>http://example.com</p>
<img src="https://i0.wp.com/wptavern.com/wp-content/uploads/2016/07/stack-overflow.png?ssl=1" />
<input type="text" id="copy" style="opacity:0;height:0;width:0" />
</a>
This question already has answers here:
Programmatically change the src of an img tag
(9 answers)
Closed 5 years ago.
function change(ele) {
document.getElementById('info').innerHTML = ele.alt;
document.getElementById('info').style.backgroundImage = "url(ele.src)";
}
<div id='info'>
This will tell you more about the below image
</div>
<div id='container'>
<div>
<img alt="The mini Barbarian" src="img\barbarian-thumb.jpg" class="pics" onmouseover="change(this)">
</div>
</div>
how do i change the background image of div with id info with the image on which the mouse hover that image is in div tag with id conatiner
please see this. Basically you can bind function inline with html. Or you can bind it dynamically. This is very simple solution. If your image path is fixed.
<script type="text/javascript">
function mouseaway(my_image) {
my_image.src = "someimage.jpg";
}
function rollover(my_image) {
my_image.src = "someimage2.jpg";
}
</script>
<img src="someimage3.jpg" onmouseover="rollover(this)" onmouseout="mouseaway(this)" />
Just assign an id to your image tag and change the image src like this.
function mouseOverImage() {
document.getElementById("img").src = "images/foo.png";
}
<img
id="img"
alt="some description/info"
src="images/blue.png"
onmouseover = "mouseOverImage()"
/>
Hope this will help
$(document).ready(function(){
$("img").hover(function(){
$(this).attr('src', 'images/alt/imagename.jpg');
});
});
Try this:
function change(e){
document.getElementById("info").style.backgroundImage = "url('"+e.src+"')";
document.getElementById("info").style.backgroundRepeat="no-repeat";
}
function change2(e){
document.getElementById("info").style.backgroundImage = "";
}
#info{
height:100px;
}
<div id='info'>
This will tell you more about the below image
</div>
<div id='container'>
<div>
<img alt="The mini Barbarian" src = "data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2264%22%20height%3D%2264%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2064%2064%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_1614068cdea%20text%20%7B%20fill%3Argba(255%2C255%2C255%2C.75)%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A10pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_1614068cdea%22%3E%3Crect%20width%3D%2264%22%20height%3D%2264%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2213.84375%22%20y%3D%2236.5%22%3E64x64%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" class="pics" onmouseover="change(this)" onmouseout="change2(this)">
</div>
</div>
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 6 years ago.
I'm trying to append a child to a td element. here is the HTML I am working with,
<td colspan="8" class="sectionExpandColumn courseResultLL courseResultLR">
<a class="sectionExpand collapsibleCriteria" action=sectionDetail">
sections
</a>
</td>
I want it to be,
<td colspan="8" class="sectionExpandColumn courseResultLL courseResultLR">
<a class="sectionExpand collapsibleCriteria" action=sectionDetail">
sections
</a>
<a class="sectionExpand collapsibleCriteria" action=sectionDetail">
discussion
</a>
</td>
just simply addding a link tag under td, really.
so in my script,
div = table.getElementsByClassName("sectionExpandColumn");
var button = document.createElement("a");
button.setAttribute("class", "sectionExpand.collapsibleCriteria");
button.innerHTML = "Discussion";
div.appendChild(button);
I am getting Uncaught TypeError: div.appendChild is not a function
Why is it?
Update
Thank you for telling me that I'm working with a htmlcollection!
So I added this code,
for (var i=0; i<div.length; i++){
div[i].appendChild(button);
}
But it runs through just fine, but at the end, it only adds the element to the last div. I'm trying to make a sense out of this... Could you tell me why?
In this instance, your variable div is not an element, but an array like object. You can try:
div = table.getElementsByClassName("sectionExpandColumn");
var button = document.createElement("a");
button.setAttribute("class", "sectionExpand.collapsibleCriteria");
button.innerHTML = "Discussion";
div[0].appendChild(button);
Try this simple code:
<td colspan="8" class="sectionExpandColumn courseResultLL courseResultLR">
<a class="sectionExpand collapsibleCriteria" action="sectionDetail">
sections
</a>
</td>
Jquery:
$('.sectionExpandColumn').append('<a class="sectionExpand collapsibleCriteria" action=sectionDetail"> discussion</a>');
Try This
var div = document.getElementsByClassName("sectionExpandColumn");
var button = document.createElement("a");
button.setAttribute("class", "sectionExpand.collapsibleCriteria");
button.innerHTML = "Discussion";
div.innerHTML +=button;
This question already has answers here:
How to get an HTML element's style values in JavaScript?
(5 answers)
Closed 5 years ago.
I just want to get the maxHeight of an element previously define at css but doesnt work.
It only works if I modify it explicitly with javascript first
Code
let something=document.querySelector(".something");
let before=document.querySelector(".before");
let after=document.querySelector(".after");
before.textContent=something.style.maxHeight
something.style.maxHeight="20px";
after.textContent=something.style.maxHeight;
.before::before{
content:'Before:'
}
.after::before{
content:'After: '
}
.something{max-height:30px}
<body>
<div class="something">
Something very cool
</div>
<div class="before">
Before:
</div>
<div class="after">
After:
</div>
</body>
I did a little digging and found an answer for you, just replace your line with this:
before.textContent=window.getComputedStyle(something).maxHeight
Code
let something=document.querySelector(".something");
let before=document.querySelector(".before");
let after=document.querySelector(".after");
before.textContent=window.getComputedStyle(something).maxHeight; // the fix!!!
something.style.maxHeight="20px";
after.textContent=something.style.maxHeight;
.before::before{
content:'Before:'
}
.after::before{
content:'After: '
}
.something{max-height:30px}
<body>
<div class="something">
Something very cool
</div>
<div class="before">
Before:
</div>
<div class="after">
After:
</div>
</body>
alternatively: you can get the element current rendered height by doing so:
How do you get the rendered height of an element?