How to get the attribute of the first child of a div? - javascript

I have a div
<div id="img-1" class="cards"><img src="blah" alt="blah2"</div>
How do I define a variable that has the value of the alt attribute, without giving img a class or ID?
Thanks!

Try this
const img = document.getElementById('img-1').getElementsByTagName('img')[0];
console.log(img.alt);

document.getElementById('img-1').getFirstElementChild.getAttribute('alt');
You can use getFirstElementChild. As you can see it does not matter what your child element is as long as it exists. But if you are looking for alt you can simply query an img inside the div. alt is an image property.

One way is to use jQuery to select the div by class then find the first img element and get its alt attribute, then store that to a variable:
$(document).ready(function() {
var divCards = $('.cards');
// store the alt attribute of first image to variable
var attrValue = divCards.find('img').eq(0).attr('alt');
console.log(attrValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="img-1" class="cards">
<img src='blah' alt='blah1'>
<img src='blah' alt='blah2'>
</div>

var altValue = document.querySelector('.card > img').alt
for(var each of document.querySelectorAll('.card > img')){
var altValue = each.alt;
....
}
JQuery equivalents
$(`.card > img`).attr('alt')
$(`.card > img`).each(function(index){ // each is bound to this
var altValue = $(this).attr('alt');
});
> forces that the img tag lies directly below the .card element

firstChild.alt should do the trick:
const alt = document.querySelector('.cards').firstChild.alt;
console.log(alt);
<div id="img-1" class="cards"><img src='blah' alt='blah2'></div>
Alternatively you can use the first-child CSS selector:
const alt = document.querySelector('.cards > *:first-child').alt;
console.log(alt);
<div id="img-1" class="cards"><img src='blah' alt='blah2'></div>

Related

How to target tag after a class?

<div class="pre-class">
<div>100%</div>
</div>
I'm trying to remove the percent (%) on the text inside the div after the class pre-class with textContent.replace("%","") but I just can't target that specific div
(I'm working on a longer website with a lot of divs and I can't add an ID to it because it's from a shortcode.)
I thought I could do something like this:
var textContent = document.getElementsByClassName('gamipress-progress-bar-completed').getElementsByTagName('div');
You're basically there. Don't forget that getElementsByClassname returns an array, so simply use [0] to retrieve the element. You'll see it working in the snippet below:
var textContent = document.getElementsByClassName('pre-class')[0].getElementsByTagName('div')[0].innerHTML;
console.log(textContent)
<div class="pre-class">
<div>100%</div>
</div>
You can use querySelector
let div = document.querySelector('div.pre-class > div');
div.innerText = div.innerText.replace('%', '')
<div class="pre-class">
<div>100%</div>
</div>
If the div will be the first direct child of the pre-class div, and you have one element with "pre-class" class, this will work
const textContent = document.querySelector('.pre-class').firstElementChild.textContent;
console.log(textContent.replace('%', ''))
<div class="pre-class">
<div>100%</div>
</div>
const content = document.querySelector('.pre-class > div').innerHTML;
content.replace("%", "");
<div class="pre-class">
<div>100%</div>
</div>
This is another way of selecting the div nested in your .pre-class div. Perhaps not the best way of doing this but it's handy to know querySelector works.
If you have lots of divs inside div.pre-class , its better to add specific data attribute to each child div and select the desired div using this:
< div class = 'pre-class' >
<div data-order = 'first' > 1 < /div>
<div data-order = 'second' > 2 < /div>
<div data-order = 'third' > 3 < /div>
</div>
///////////
document.querySelector('div[data-order="first"]')
let containers = document.getElementsByClassName("pre-class");
for (var i = 0; i<containers.length; i++) {
let current = containers[i];
let textNode = current.children[0];
textNode.innerText = textNode.innerText.replace(/(\d)%/, '$1');
};
<div class="pre-class">
<div>100%</div>
</div>
Alternatively, you could use element.querySelector() (or querySelectorAll) to find the correct element(s) to replace.
let textNode = document.querySelector(".pre-class > div"); // use querySelectorAll in case there can be multiple matches.
textNode.innerText = textNode.innerText.replace(/(\d)%/, '$1');
<div class="pre-class">
<div>100%</div>
</div>
Use the child selector (>).
let textDiv=document.querySelector(".pre-class > div");
textDiv.textContent=textDiv.textContent.replace("%","");
This will replace the first direct div inside .pre-class. You can adjust the position of divs using pseudo classes. Like for example, if you want to select the second div inside .pre-class, you would use:
<div class="pre-class">
<div>100%</div>
<div>200%</div>
<div>300%</div>
</div>
let textDiv=document.querySelector(".pre-class > div:nth-child(2)");
textDiv.textContent=textDiv.textContent.replace("%","");

How get src value when click on one of the mulitple images in javascript?

I have 3 images in my web page. I want to get src value every time when I clicked on any image. I tried following code but its not working with multiple images.
<div class="test">
</div>
</div>
</div>
</div>
<script type="text/javascript">
function filename(){
//var fullPath = document.getElementsByClassName('dImage').src;
var fullpath = document.getElementsByClassName('dImg').src
console.log(fullPath);
var filename = fullPath.replace(/^.*[\\\/]/, '');
var fileid = filename.split("\deckel.")[0];
//window.location.href = "web-rocketcreator.html?="+fileid;
console.log(fileid);
}
</script>
As the other answers have mentioned the specific problem area, here's an alternative solution.
Instead of attaching a click event to each image you can attach one to the container and listen for events as they bubble up the DOM (known as event delegation.)
// Grab the container, and add an event listener to it
const imageContainer = document.querySelector('.test');
imageContainer.addEventListener('click', filename, false);
function filename(event) {
// Pick out the src attribute from target element
// (the image that was clicked on)
const { target: { src } } = event;
// Use the src as the basis for the rest of
// your calculations
var filename = src.replace(/^.*[\\\/]/, '');
var fileid = filename.split("\deckel.")[0];
console.log(`web-rocketcreator.html?=${fileid}`);
}
.test a {
display: block;
}
<div class="test">
<a href="#" class="part-one">
<img class="dImage" src="images/deckel-1.png" alt="">
</a>
<a href="#" class="part-one">
<img class="dImage" src="images/deckel-2.png" alt="">
</a>
<a href="#" class="part-one">
<img class="dImage" src="images/deckel-3.png" alt="">
</a>
</div>
To get a reference to the object which triggered the click event you need to pass the keyword this as a parameter.
In your case this object is the <a> element. To get it's nested children - the <img> element you need to call the .children method which returns an array. Since there's just the image element you can directly reference it using children[0] and ultimately add the .src property to retrieve the source.
function filename(element){
console.log(element.children[0].src);
}
<div class="test">
</div>
Get src value from image when clicking on it
When you call a function from onClick() you can pass 'this' to the function. This way you will directly have a reference to the clicked element inside the functon
<img src="xxxx.jpg" onclick="myFunction(this)" />
function myFunction(element) {
const src = element.src;
}
Get src value from image when clicking on parent container
<a onclick="myFunction(this)"><img src="xxxx.jpg" /></a>
function myFunction(link) {
const src = link.children[0].src
}

creating a link to images

I am trying to create a jquery code which can wrap an img tag with a link:
My code is like this:
http://prntscr.com/iuw6hc
I will paste my HTML here but basically it is a loop of many items showing within each col.
<div class="car-item gray-bg text-center first" style="height: 357px;">
<div class="car-image">
<img class="img-responsive" src="http:///wp-content/uploads/2018/03/20180214_090633-265x190.jpg" alt="" width="265" height="190">
<div class="car-overlay-banner">
<ul>
<li><i class="fa fa-link"></i></li>
I am trying like this:
var wrapped = false;
var original = $(".img-responsive");
$(".img-responsive").click(function(){
if (!wrapped) {
wrapped = true;
var gURL = $('.car-overlay-banner').find('a').attr('href');
$(".img-responsive").wrap("");
}
});
$(".img-responsive").click(function(){
if (wrapped) {
wrapped = false;
$(".img-responsive").parent().replaceWith(original);
}
});
Trying to use a href of car overlay to apply to the image too.
jQuery provides a method named "wrap()", which can be used to insert any HTML structure in set of matched elements. In simple words, if you want put wrapper around your div element then you can use wrap() method. For example, you have a div with ID "Child".
<div id="Child"></div>
And want to wrap this div with any parent then you can use "wrap()" method to insert HTML.
$('#Child').wrap('<div id="Parent"></div>');
<div id="parent">
<div id="child"></div>
</div>
Same way, we will use the wrap() method to insert hyperlink to image tag so that the image becomes clickable. See below.
$(document).ready(function() {
$("#imgLogo").wrap('');
});
In this example, I have used ID as selector but you can use class selector to find all the images with same class and then wrap them with tag. You can also assign target="_blank" in the above tag to open the link in new window.
I think you need code like this?
var wrapped = false;
var original = $(".img-responsive");
$(".img-responsive").click(function(){
if (!wrapped) {
var wrapped = true;
// find link href in .car-image(img-responsive's parent)
var gURL = $(this).parent().find('a').attr('href');
// use $(this) instead of $(".classname") to apply link only clicked image
$(this).wrap("");
}
});
$(".img-responsive").click(function(){
if (wrapped) {
var wrapped = false;
$(this).parent().replaceWith(original);
}
});

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";

javascript - how to get img tags from any element?

I want to get img tags attribute values from any element, img tags could be more than 1, and also can be randomized.
like,
<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>
I want to grab their title attribute values and then want to store in some var currentHTML; with all existing div data.
and then insert into any element just like $('#div').html(currentHTML);
and output should be like this,
hellow :) how are u :D
How can I do this?
Thanks in advance.
Try this:
$("img").each(function()
{
$(this).replaceWith($(this).prop("title"));
});
Fiddle. Its just looping through each image and replacing it (with replaceWith()) with its own title attribute.
UPDATE:
Things got more complex. Check this snippet:
// The text result you want
var currentHTML = "";
// Instead of search for each image, we can search of elements that
// contains images and you want to get their text
$(".images").each(function()
{
// Check note #1
var cloned = $(this).clone().css("display", "none").appendTo($("body"));
// Here we select all images from the cloned element to what
// we did before: replace them with their own titles
cloned.find("img").each(function()
{
$(this).replaceWith($(this).prop("title"));
});
// Add the result to the global result text
currentHTML+= cloned.html();
});
// After all, just set the result to the desired element's html
$("#div").html(currentHTML);
Note #1: Here is what is happening in that line:
var cloned = here we create a var which will receive a cloned element;
the cloned element will the current element $(this).clone();
this element must be hidden .css("display", "none");
and then appended to the document's body .appendTo($("body"));.
Note that in your initial html, the div containing the images received the class images:
<div class="images"> hellow <img src='icons/smile.png' title=':)' /> how are u <img src='icons/smile2.png' title=':D' /></div>
So you can do that on more than one element. I hope this helps.
Here's a neat little function you can reuse.
$(function(){
function getImageReplace($el) {
var $copy = $el.clone();
$copy.find('img').each(function(){
$(this).replaceWith($(this).attr('title'));
});
return $copy.text();
}
//now you can use this on any div element you like
$('#go').click(function() {
alert(getImageReplace($('div')));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>
<button id='go'>Convert images</button>

Categories