I need to get values inside div on clicking a button, wich locates inside this div. Here is the html structure:
<div class="products__item">
<div class="products__content">
<a class="products__title" href="#">Altec Lansing Octiv Duo M202 акустическая система акустическая система</a>
<div class="products__priceholder">
<p class="products__price"><strong>86 590</strong> руб.</p>
<small class="products__id">ID. 10906</small>
</div>
<p class="exist">В наличии</p>
<div class="products__buttonholder">
Купить
</div>
</div>
</div>
When I click on .button-buy-modal, I need to get values from .products__title .products__price and .products__id, but the problem is that we have a lot same div's (product cards), and a lot of buttons inside them. I think that I should use something like $(this), but actually I don't know how.
I'm trying to test something like this, but it doesn't work:
$("a.button-buy-modal").click(function () {
$(this).find().closest('.products__priceholder').addClass('test1');
})
Here is a solution:
$("a.button-buy-modal").click(function () {
var prTitle = $(this).parent().parent().children('.products__title').html();
var prPrice = $(this).parent().parent().children('.products__priceholder').children('.products__price').children('strong').html();
var prId = $(this).parent().parent().children('.products__priceholder').children('.products__id').html();
var prImage = $(this).parent().parent().parent().children('.products__imageholder').children('.products__thumbnail').attr('src');
console.log(prTitle);
console.log(prPrice);
console.log(prId);
console.log(prImage);
})
$(this).parent().parent().find('.products__price').text()
will give you this - "86 590 руб."
$(this).parent().parent().find('.products__price').html()
will give you this -- "<strong>86 590</strong> руб."
To learn more about it as in how you can select any particular DOM element and read it or manipulate it etc, read here - http://api.jquery.com/category/selectors/
You can add an id to your parent div or use eq(x) to select the right group.
<div id="mydiv1" class="products__item">
<div class="products__content">
<a class="products__title" href="#">Altec Lansing Octiv Duo M202 акустическая система акустическая система</a>
<div class="products__priceholder">
<p class="products__price"><strong>86 590</strong> руб.</p>
<small class="products__id">ID. 10906</small>
</div>
<p class="exist">В наличии</p>
<div class="products__buttonholder">
Купить
</div>
</div>
</div>
Then with jQuery:
var title = $('#div1 .products__title').html();
/// OR
var title = $('.products__item:eq(0) .products__title').html();
var price = $('#div1 .products__price').html();
/// OR
var price = $('.products__item:eq(0) .products__price').html();
price = price.replace(/<[^>]+>/g, ""); // regex to remove tags
EDIT
If you want to use .closest(), you don't need .find()
$("a.button-buy-modal").click(function () {
$(this).closest('.products__priceholder').addClass('test1');
});
Thank's all for advices, I found a solution:
$("a.button-buy-modal").click(function () {
var prTitle = $(this).parent().parent().children('.products__title').html();
var prPrice = $(this).parent().parent().children('.products__priceholder').children('.products__price').children('strong').html();
var prId = $(this).parent().parent().children('.products__priceholder').children('.products__id').html();
var prImage = $(this).parent().parent().parent().children('.products__imageholder').children('.products__thumbnail').attr('src');
console.log(prTitle);
console.log(prPrice);
console.log(prId);
console.log(prImage);
})
Related
I am trying to pass an ID with a function to another function. The console then informs me that there is a TypeError: document.getElementById(...) is null. The javascript file is appended at the end and I also tried adding the code into a self executing function, but that didn't solve the problem.
Basically I would like to an addEventListener to the sub-category divs (buttons) and they should pass their value to another function.
The error is pointing at this line let mainCategory = document.getElementById(recived_value).parentNode.firstChild(this.id); so recived_value is null.
Any help would be welcome. Thank you.
HTML:
<div class="wrapper">
<div class="main-category" id="box">
Boxes
</div>
<div class="sub-category" id="b_small">
Small Boxes
</div>
<div class="sub-category" id="b_medium">
Medium Boxes
</div>
<div class="sub-category" id="b_large">
Large Boxes
</div>
</div>
JS:
var subCategoryClass = document.querySelectorAll(".sub-category");
var subCategoryArray = Array.from(subCategoryClass);
for ( let i = 0; i < subCategoryArray.length; i++ ){
subCategoryArray[i].addEventListener("click", PassValue(this.id));
}
function PassValue(recived_value){
let subCategory = recived_value;
let mainCategory = document.getElementById(recived_value).parentNode.firstChild(this.id);
TwoArgFunc(mainCategory, subCategory);
}
There were a couple of problems. I described them below in // comments.
Edit: Based on your comment, I changed to a normal function definition.
var subCategoryClass = document.querySelectorAll(".sub-category");
var subCategoryArray = Array.from(subCategoryClass);
for ( let i = 0; i < subCategoryArray.length; i++ ){
subCategoryArray[i].addEventListener("click", function(ev) { PassValue(ev.target.id)} ); // need a function here, not just a statement
}
function PassValue(recived_value){
console.log(recived_value);
let subCategory = recived_value;
let mainCategory = document.getElementById(recived_value).parentNode.firstElementChild.id; // use firstElementChild because firstChild is a newline text node
console.log(mainCategory);
// TwoArgFunc(mainCategory, subCategory);
}
<div class="wrapper">
<div class="main-category" id="box">
Boxes
</div>
<div class="sub-category" id="b_small">
Small Boxes
</div>
<div class="sub-category" id="b_medium">
Medium Boxes
</div>
<div class="sub-category" id="b_large">
Large Boxes
</div>
</div>
Above PassValue function put:
var that = this;
And then in your PassValue function pass that.id:
... .firstChild(that.id);
Hi everyone I want to extract data from divs using Jquerys.
So I have this 3 div :
<div class="wind">Venice,it</div>
<div class="wind">Madrid,es</div>
<div class="wind">Rome,it</div>
In my JS file I want to extract: Venice,it / Madrid,es / Rome,it.
What I did for now is: var data = $("div.wind").text() .
Writing this I get the string Venice,itMadrid,esRome,it but I don't want to this. I want the div splitted already like.
var vector= [(Venice,it),(Madrid,es),(Rome,it)]
How can I do this?
Thank you in advance for your help.
Use .each()
$(() => {
var vector = []
$(".wind").each(function(){ vector.push($(this).text()) })
console.log(vector)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wind">Venice,it</div>
<div class="wind">Madrid,es</div>
<div class="wind">Rome,it</div>
const divs = $("div.wind");
const data = divs.toArray().map(d => d.textContent)
just use push on the innerHTML
var myArray=[];
var div =document.getElementsByTagName('div');
for(let i=0;i<div.length;i++){
myArray.push(div[i].innerHTML);
}
console.log(myArray);
<div class="wind">Venice,it</div>
<div class="wind">Madrid,es</div>
<div class="wind">Rome,it</div>
You can use jQuery's .each to iterate through each div selected. You can then get the .text() value for each div one by one, and push the value into the vector array.
Demo:
var vector = [];
$("div.wind").each(function(index, div) {
var data = $(div).text();
vector.push(data);
});
console.log(vector);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wind">Venice,it</div>
<div class="wind">Madrid,es</div>
<div class="wind">Rome,it</div>
I'm trying to make a custom data attributes on my website in lightbox. I just made it for one element in Javascript and it works fine but I want to make it works in multiple elements.
How it works now: I have "a" element with id="image-1" and I want to make that javascript will recognise id image-2,3,4... and show correct data from custom attributes. Note that I can't use onclick because it makes that lightbox stops work.
Here is HTML:
<div class="col-xs-12 col-sm-4 col-md-3 col-lg-3">
<div class="thumbnail grid-wrapper thumbnail-single">
<a id="image-1" href="img/photo2.jpeg" data-tags="<li>t31232est</li> <li>test</li>" data-fb="http://test1.pl" data-tt="http://test2.pl" data-gplus="http://te23432st3.pl" data-lightbox="roadtrip" data-title="This is a caption. This is a caption This is a caption This is a caption"><img src="img/photo2.jpeg" class="img-responsive" alt="..."></a>
</div>
</div>
<div class="col-xs-12 col-sm-4 col-md-3 col-lg-3">
<div class="thumbnail grid-wrapper thumbnail-single">
<a id="image-2" href="img/photo3.jpg" data-tags="<li>test</li> <li>test</li>" data-fb="http://test55.pl" data-tt="http://test253342.pl" data-gplus="http://tes32423t3.pl" data-lightbox="roadtrip" data-title="This is a caption. This is a caption This is a caption This is a caption"><img src="img/photo3.jpg" class="img-responsive" alt="..."></a>
</div>
</div>
Here is JS:
var global = document.getElementById('image-1');
var tagList = global.getAttribute('data-tags');
var facebook = global.getAttribute('data-fb');
var twitter = global.getAttribute('data-tt');
var gplus = global.getAttribute('data-gplus');
$('<div id="lightboxOverlay" class="lightboxOverlay"></div><div id="lightbox" class="lightbox"><div class="lb-outerContainer"><div class="lb-container"><img class="lb-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" /><div class="lb-nav"><a class="lb-prev" href="" ></a><a class="lb-next" href="" ></a></div><div class="lb-loader"><a class="lb-cancel"></a></div></div></div><div class="lb-dataContainer"><div class="lb-data"><div class="lb-details"><ul class="tag-list">' + tagList +'</ul><br/><span class="lb-caption"></span><span class="lb-number"></span></div><div class="lb-closeContainer">' +
'<ul class="social-list"><li><img src="img/fb_circle_white.png" class="img-responsive"></li><li><img src="img/tt_circle_white.png" class="img-responsive"></li><li><img src="img/gplus_circle_white.png" class="img-responsive"></li></ul><a class="lb-close"></a></div></div></div></div>').appendTo($('body'));
I'm trying to make it works on Lightbox Plugin (http://lokeshdhakar.com/projects/lightbox2/)
UPDATE
I just used function in onclick and when I'm testing it, it shows correct IDs. But still can't put it into getElementByID as a string.
id="image-1" onclick="GetID(this.id)"
window.GetID = function(elem_id){
alert(elem_id);
}
var global = document.getElementById(GetID());
var tagList = global.getAttribute('data-tags');
var facebook = global.getAttribute('data-fb');
var twitter = global.getAttribute('data-tt');
var gplus = global.getAttribute('data-gplus');
UPDATE 2:
Almost done. I've made my variables global. Console log shows correct ID and other data attribs. Problem is when I'm trying to put result into html in javascript. Here is example.
<ul class="social-list"><li><img src="img/fb_circle_white.png" class="img-responsive"></li>
+ current JS:
id="image-1" onclick="window.GetID(this.id)"
var global;
var tagList;
var facebook;
var twitter;
var gplus;
window.GetID = function(elem_id){
console.log(elem_id);
global = document.getElementById(elem_id);
console.log(global);
tagList = global.getAttribute('data-tags');
console.log(tagList);
facebook = global.getAttribute('data-fb');
console.log(facebook);
twitter = global.getAttribute('data-tt');
console.log(twitter);
gplus = global.getAttribute('data-gplus');
console.log(gplus);
}
+ image of console response.
A good solution would be to get the id attribute of 'a' element when clicking it put it in a var and use it to get data attributes.
Assuming 'a' elements are inside a div '#container' here is my solution
$('#container a').click(function(){
var image_id = '#' + $(this).attr('id');
var tagList = $(image_id).data('tags');
var facebook = $(image_id).data('fb');
var twitter = $(image_id).data('tt');
var gplus = $(image_id).data('gplus');
});
not sure if I am understanding correctly. But if the id of the divs are consistent, meaning image-1, image-2, image-3,... and so on, you could use and expression selector and loop through the number of elements in that array to add/append your dynamic html inside those divs without using a click event to get the id. Ex -
var array_of_divs = $("div[id^=image-]") // this gives you an array of all the element having the id starting with 'image-'
further you can loop though the length of this array and add your dynamic html based on the id of the parent : ("image-"+counter_variable])
let me know if this helps.
I have a have several divs on a page called parent_container inside it I have a heading, image and a button
how can I get the value for the specific heading of the container it was clicked from?
<div class="parent_container">
<img class="news_image" src="/" />
<h1 class="product_title">title 1</h1>
<a class="cta-btn" href="#">button1</a>
</div>
<div class="parent_container">
<img class="news_image" src="/" />
<h1 class="news_title">title 2</h1>
<a class="cta-btn" href="#">button2</a>
</div>
//getting the elements
var update_buttons = document.getElementsByClassName( 'cta-btn' ),
parentElement = document.getElementsByClassName( 'parent_container' ),
itemTitle = document.getElementsByClassName( 'news_title' );
//trying to get the title from the div it was clicked in
var getTitle = function( evt ) {
var title = this.itemTitle;
console.log( title ); //undefined
}
//setting up a event listener on all the buttons on the page
for( var i=0;i<update_buttons.length;i++ ){
update_buttons[i].addEventListener('click', getTitle);
}
Get the clicked element using evt.toElement (In this case, this works too, though).
From there, get the parent node, and then select the child h1 element.
Access the text using textContent:
var getTitle = function (evt) {
var el = evt.toElement, // or this
parent = el.parentNode,
header = parent.querySelector('h1[class*="title"]'),
headerText = header.textContent;
console.log(headerText);
}
Example Here
..and if you prefer not to cache variables:
evt.toElement.parentNode.querySelector('h1[class*="title"]').textContent;
//getting the elements
var update_buttons = document.getElementsByClassName('cta-btn'),
parentElement = document.getElementsByClassName('parent_container'),
itemTitle = document.getElementsByClassName('news_title');
//trying to get the title from the div it was clicked in
var getTitle = function (evt) {
var el = evt.toElement,
parent = el.parentNode,
header = parent.querySelector('h1[class*="title"]'),
headerText = header.textContent;
console.log(headerText);
}
//setting up a event listener on all the buttons on the page
for (var i = 0; i < update_buttons.length; i++) {
update_buttons[i].addEventListener('click', getTitle);
}
<div class="parent_container">
<img class="news_image" src="/" />
<h1 class="product_title">title 1</h1>
<a class="cta-btn" href="#">button1</a>
</div>
<div class="parent_container">
<img class="news_image" src="/" />
<h1 class="news_title">title 2</h1>
<a class="cta-btn" href="#">button2</a>
</div>
Solution with the least steps. It seams that your title is always the previous element of the button.
Use:
var getTitle = function( evt ) {
var title = this.previousElementSibling.textContent || this.previousElementSibling.innerText;
console.log( title ); //undefined
}
To be sure that you always return the correct element you need a bit more than the sample above. Why am I saying this. If you (or someone else) edits the html the solution above could break. A better solution is to give the title element a class name or better an attribute that is only used for those titles. Take a look at this solution:
<div class="parent_container">
<img class="news_image" src="/" />
<h1 title-element class="news_title">title 2</h1>
<a class="cta-btn" href="#">button2</a>
</div>
var getTitle = function( evt ) {
var title = this.parentElement.querySelector("h1[title-element]");
return title.textContent || title.innerText;
}
The above answer makes it less likely that your function breaks when the html gets updated in the future.
PS. The || element.innerText is a fall back for older browsers (read IE) that don't support textContent.
First you got a typo: console.log(title). And here is what you need to do, get the parent, then the child for the header:
var title = this.parentNode.children[1].innerHTML;
console.log( title );
Example Here
Note this assumes that you have the same structure for the <div class="parent_container"> item, such that the title is the second item.
Edit
If the structure is changed you can select the item with querySelector('h1'):
var title = this.parentNode.querySelector('h1').innerHTML;
console.log( title );
As #JoshCrozier proposed you can use .querySelector('h1[class*="title"]') which means it selects some class with the word "title" in it. So product_title, news_title, something_title will work. That way you can have other <h1> elements in the <div> as well if you happen to want to add them (you just have to make sure they don't have a class with the word "title" in those).
I tried it with getElementById and it worked. But now I want the same with multiple div's so I have to use classes. So I changed the method to getElementsByClassName and now it says undefined.
(The function is called when a option in a select changes. This works correctly)
HTML:
<div class="item_content">
<h3 class="filmnaam">22 jump street</h3>
</div>
<div class="item_content">
<h3 class="filmnaam">rio 2</h3>
</div>
Javascript:
function sorting(sortingway) {
alert(sortingway.value);
var titelfilms = document.getElementsByClassName("filmnaam");
var titels = titelfilms.innerHTML;
console.log(titels[0]);
}
Is there a way to do this without jQuery?
getElementsByClassName returns a collection, so loop that!
var titelfilms = document.getElementsByClassName("filmnaam");
for (var i = 0; i < titelfilms.length; i++) {
var titels = titelfilms[i].innerHTML;
console.log(titels);
}
titelfilms is a node list, you can't get the innerHTML of a node list as a whole, it contains multiple references to elements which each have their own individual property.
You could loop through and concatenate each innerHTML onto a variable, or you could map() the innerHTML of your returned elements to an array and then join() them up:
function sorting(sortingway) {
var titelfilms = document.getElementsByClassName("filmnaam");
var titels = Array.prototype.map.call(titelfilms, function (el) {
return el.innerHTML;
}).join(' ');
console.log(titels);
}
sorting();
<div class="item_content">
<h3 class="filmnaam">22 jump street</h3>
</div>
<div class="item_content">
<h3 class="filmnaam">rio 2</h3>
</div>