Find Elements in Javascript - javascript

I need to find a div with class "kinder" that have a element "a". I need to get and alert the href attribute from a.
UPDATED EXEMPLE: For example. If I had:
<div class="controls-wrapper">
<div class="title" role="contentinfo">
<header>
<div class="kinder" aria-hidden="true">
<a tabindex="-1" href="https://google.com" target="_blank">
<img src="https://imageUrl/120x120.jpg" alt="" width="60" height="60">
</a>
</div>
I need to alert "http://google.com"
I have tried the following code:
var aUserVideo = document.getElementsByClassName('kinder')
aUserVideoHref = aUserVideo.attribute("a");
aUserVideoHref = aUserVideoHref.attribute("href");
alert(aUserVideoHref);

Problems:
The javascript method getElementsByClassName() return array-like object of all child elements which have all of the given class names, so you've to target the object you want to use by index (example to get the first use aUserVideo[0]).
If you want to get an attribute you should use getAttribute() instead of attribute.
Suggested Solution :
You could simply get the href using querySelector with .href like :
document.querySelector(".kinder a").href
Hope this helps.
window.addEventListener("DOMContentLoaded", function() {
console.log(document.querySelector(".kinder a").href);
}, false);
<div class="kinder" aria-hidden="true"> <a tabindex="-1" href="http://google.com" target="_blank"> <img src="https://imageUrl/120x120.jpg" alt="" width="60" height="60"> </a> </div>

You have your post tagged with jQuery. Here's the jQuery way to do it:
alert( $('.kinder a').prop('href') );
Or vanilla JavaScript:
alert ( document.querySelectorAll('.kinder a')[0].href );

You can get it with Jquery using the attr function like this:
Jquery:
alert($('.kinder a').attr('href'));
Regards!

Related

How Can I Use th:data-url

I need to take the number of id from:
<div class="social" th:data-url="#{http://localhost:8080/poll?id=${poll.pollId}" data-title="">
But this does not work. How can I do it?
Hope this helps.
$(document).ready(function(){
//get value of 'this' element that was clicked
var url = $(this).attr('data-url');
// split string and get value of id
var splitted = url.split("id=");
console.log("Id:"+splitted[1]);
});
Or bind onclick or onchange event
<div class="social" th:data-url="#{http://localhost:8080/poll?id=${poll.pollId}" th:onclick="'getId(\''+ ${poll.pollId} +'\')'" data-title="">
And get the id value
<script type="text/javascript">
function getId(id) {
console.log(id);
}
</script>
All the custom attributes are defined using th:attr attribute. Like:
<div class="social" data-title=""
th:attr="data-url=#{|/poll?id=${poll.pollId}|}" data-title="">
Also specifying #{} with the URL or href will build the complete URL.

How can I change the src in this html tag.I want to change src to some thing else

<div class="logo">
<a href="somelink.com">
<img src="someimage.png">
</a>
</div>
I want to change the src,how can I chage this src by using documents.getElementsByClassName.
You can not use getElementsByClassName because you don't have any classes associated with it.
You could however use a querySelector and get the class of the div and find the child that way. So with this html:
<div class="logo">
<a href="somelink.com">
<img src="someimage.png">
</a>
</div>
We can then use:
let img = document.querySelector('.logo img')
img.src = '/path/to/new/image.png'
.logo this is the class to find
img this is the child element of .logo
It doesn't have to be a direct child since there was no >
Once we have gotten that image we then set the new src to something else and the browser will automatically load the new image (assuming it exists).
try this
document.getElementsByClassName('img_ad')[0].src ='your source'
and add 'img_ad' class in the img element
<div class="logo">
<a href="somelink.com">
<img class="img_ad" src="someimage.png">
</a>
</div>
You can give the img tag an id and use:
document.getElementById("someid").src= "path/to/src";
or:
document.querySelector("#someid").src = "path/to/src";
Add an ID to the <img> (Example: id="myImage") and in JavaScript use the following:
document.getElementById("myImage").src = "newImage.png";

jQuery on click redirect to child href attribute

I'm trying to link one div with the href attribute of his first <a> href.
My html looks like this
<div class="clicked">
<a class="i-want-this-href" href="target">
<img>
</a>
<a class="this-one-is-useless" href="Wrong-target">
<img>
</a>
</div>
And I have tested some different ways like this:
$('.clicked').on('click',function(){
aux= $('this:first-child').attr("href");
console.log(aux);
});
But I always get Undefined on the console. And I want to get "target" inside the first <a> element.
Any help will be appreciated!
Your selector is incorrect, you can use .find()/.children() along with :first selector
aux= $(this).find('a:first').attr("href");
Use this context along with :first-child selector
$('.clicked').on('click', function() {
var href = $(this).find('a:first-child').attr("href");
console.log(href);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="clicked">
<a class="i-want-this-href" href="target">
<img>
</a>
<a class="this-one-is-useless" href="Wrong-target">
<img>
</a>
1) Do not use this in selectors, this needs to be passed to $ separately
2) Make sure to declare variable as local, otherwise there will be bugs.
3) Use first-of-type
$('.clicked').on('click',function(){
var aux = $(this).find('a:first-of-type').attr("href");
console.log(aux);
});
$('.clicked').on('click',function(){
aux= $(this).find('a:first-child').attr("href");
console.log(aux);
});
Wrong selector, If you want to use this in selector you should pass it separared as follows :
var aux = $('a', this).prop("href");
//Or
var aux = $(this).find('a').prop("href");
NOTE : jQuery by default will select the first occurrence.
Hope this helps.
$('.clicked').on('click',function(){
var aux = $('a', this).prop("href");
console.log(aux);
});
.clicked{
width:100%;
height:100px;
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clicked">
<a class="i-want-this-href" href="target">
Image 1
</a>
<a class="this-one-is-useless" href="Wrong-target">
Image 2
</a>
</div>

jQuery find closest

I'm trying to get the a href of an list item.
HTML
<div class="popup" style="display: none;">
<div class="product">
<div class="photo">
<a href="" class="sendkleur" id="link69"> <!-- href im trying to reach -->
<img id="product-collection-image-69" src="" alt="Test kleur" class="popup-image69">
</a>
</div>
<a href="" class="sendkleur" id="link69">
<strong>Test kleur</strong>
</a>
<span class="swatchLabel-category">Kleur:</span>
<p class="float-clearer"></p>
<div class="swatch-category-container" style="clear:both;" id="ul-attribute137-69">
<img onclick="listSwitcher();" src="" id="a137-32" class="swatch-category" alt="Beige" width="12px" height="12px" title="Beige">
<img onclick="listSwitcher();" src="" id="a137-36" class="swatch-category" alt="Zwart" width="12px" height="12px" title="Zwart">
</div>
<p class="float-clearer"></p>
</div>
</div>
There are multiple popups on the site and thats what makes it difficult. At first I used this code
var link = jQuery('.photo').find('a')[0].getAttribute("href");
But this ofcourse only returns the href of the first popup. Then I tried this code:
var link = jQuery('.photo').closest('a').attr("href");
But this returned undefined
Then I tried this:
var link = jQuery(this).closest('a').attr("href");
But that also returns undefined
Edit
Here is the whole jQuery code snippet
jQuery(document).ready(function(){
jQuery('.swatch-category-container img').click(function(){
var kleur = jQuery(this).attr('title');
var link = jQuery('.photo').find('a').attr("href");
console.log(link);
link += "?kleur="+kleur;
console.log(link);
jQuery('.photo').find('.sendkleur').attr("href", link);
});
});
Working from the .swatch-category-container img element, you can traverse the DOM to find the required a like this:
$('.swatch-category-container img').click(function() {
var link = $(this).closest('.popup').find('.photo a').prop('href');
// do something with link here...
});
If this is the .swatch-category-container img element then, the anchor is the previous to previous sibling of the ancestor swatch-category-container element
var link = jQuery(this).closest('.swatch-category-container').prev().prev().attr("href");
Since you said multiple popups, the idea would be like this.
1. Get all popups
2. From each popup in all popups
Get the photo href item
$('.popup').each(function() {
var hrefItem = $(this).find('.photo a').attr('href');
//Do your processing with href item
});

Launch fancyBox from button click

Im stuck with a little problem with fancyBox v2.
I want to launch fancyBox on button click. Once clicked, it will load all the images from the list (from the src attribute of the ).
I have created this jsfiddle to show what I am trying to do: http://jsfiddle.net/fPFZg/
jQuery(document).ready(function($) {
$('button').on('click', function() {
$.fancybox();
});
});
Can anybody see how this would be possible?
I had the same question and found the following to be a simpler method:
HTML
<button class="fancybox" value="Open Fancybox">Open Fancybox</button>
<div class="hidden" id="fancybox-popup-form">
(your Fancybox content goes in here)
</div>
jQuery
$('.fancybox').click(function () {
$.fancybox([
{ href : '#fancybox-popup-form' }
]);
});
CSS
.hidden { display: none; }
Further Reading
Fancybox Docs (click the "API Methods" tab, then read up on the first method, which is called "Open").
you can use it like this:
$.fancybox.open([
{
href : 'http://fancyapps.com/fancybox/demo/1_b.jpg',
title : '1st title'
},
{
href : 'http://fancyapps.com/fancybox/demo/2_b.jpg',
title : '2nd title'
}
], {
padding : 0
});
Your code doesn't work because this $.fancybox(); doesn't tell fancybox what to open so does nothing.
What I would do, if you don't want to edit every link in your html, is:
1). add an ID to the <ul> tag so we can use that selector like
<ul id="images">
2). bind fancybox to all <a> anchors that are child of your element #images like
var fancyGallery = $("#images").find("a"); // we cache the selector here
fancyGallery.attr("rel","gallery").fancybox({
type: "image"
});
notice that we are adding a rel attribute on the fly to all anchors so they will be part of the same gallery
3). bind a click event to the button (I would recommend you to give it an ID too so it won't mess with other possible buttons in the future) that triggers the existing fancybox script as above, so with this html
<button id="fancyLaunch">Launch Fancybox</button>
use this script
$('#fancyLaunch').on('click', function() {
fancyGallery.eq(0).click(); // triggers a click
});
notice that we used the method .eq() to launch the gallery from the first item (first index in javascript is always 0)
Summarizing, your whole script may look like this :
jQuery(document).ready(function($) {
var fancyGallery = $("#images").find("a");
fancyGallery.attr("rel","gallery").fancybox({
type: "image"
});
$('#fancyLaunch').on('click', function() {
fancyGallery.eq(0).click();
});
});
See JSFIDDLE
Your html:
<ul>
<li>
<a href="http://placekitten.com/400/400" title="" class="fancybox">
<img src="http://placekitten.com/100/100" alt="" />
</a>
</li>
<li>
<a href="http://placekitten.com/400/400" title="" class="fancybox">
<img src="http://placekitten.com/100/100" alt="" />
</a>
</li>
<li>
<a href="http://placekitten.com/400/400" title="" class="fancybox">
<img src="http://placekitten.com/100/100" alt="" />
</a>
</li>
<li>
<a href="http://placekitten.com/400/400" title="" class="fancybox">
<img src="http://placekitten.com/100/100" alt="" />
</a>
</li>
Your jQuery:
$(document).ready(function() {
$('button').on('click', function() {
$.fancybox($("a.fancybox"));
});});

Categories