Hello i have cart full with Elements
This Ex of one of them
<div class="item-container cart-item">
<div>
<img border="0" onerror="src='http://www.myengravedjewelry.com/Admin/surfing.jpg'" title="Bloody Mary Style Colour Name Necklace" src="http://www.myengravedjewelry.com/Admin/surfing.jpg" alt="1009">
<div class="item-header">
<div class="item-body">
<ul class="item-ul">
<li>
<li>
<li>
<span class="bold-14">Price:14.9 </span>
</li>
<li>
<span>ShortId:1010 </span>
</li>
<li>
<span>LongId:110-01-073-10 </span>
</li>
<li>
<span class="spanDefCat">DefaultCat:334 </span>
</li>
</ul>
</div>
</div>
<div class="item-footer"></div>
</div>
When i press save i go trow each one of this element and check if DefaultCat==0
var elements = document.getElementsByClassName("cart-item");
and i try to get to this defaulCat like this
for(i=0;i<elements.length;i++){
var elementContent=elements[i].find(".spanDefCat").html();
var vars = elementContent.split(" ");
var obj = {};
vars.forEach(function(v) {
var keyValue = v.split(":");
obj[keyValue[0]] = keyValue[1];
});
DefaultCat = obj["DefaultCat"];
ShortId = elements[i].children[1].alt;//New style to take ShortID
if(DefaultCat==0)setDefaultCatToProductId(parseInt(ShortId));
arrSortedOrder[i]=parseInt(ShortId);
}
Any one know how to get to this value?
p.s
Plz Do NOT give me solution with $(.spanDefCat) because when i find deff=0 i need to take ShordId as Well from this element[i]
Try this:
$(".cart-item").each(function(){
var shortId = $(this).find(".bold-14").parent("li").siblings("li").children("span").html();
var shortItem = shortId.replace(' ','').split(":");
var defaultCat = $(this).find(".spanDefCat").html();
var item = defaultCat.replace(' ','').split(":");
if(item[1]==0){
var id = parseInt(shortItem[1]);
//do something
}else{
var id = parseInt(shortItem[1]);
//do something else
}
console.log(defaultCat);
console.log(shortId);
});
Note: Above code give you the DefaultCat:334 and ShortId:1010 so now you can use both in if else statement.
If the format of DefaultCat:334 is same for all cart item then you can check whether it is 0 or not
JSFIDDLE DEMO
I see JQuery tag so i give you a response with JQuery statements.
$(".cart-item").find(".spanDefCat").each(function(index, domEle){
//get text, delete spaces and split
split_result = $(domEle).text().replace(' ','').split(":");
//get only numeric value as string
defaultCat = split_result[1];
//parse into int
defaultCat = parseInt(defaultCat);
//if your var is equal to 0
if(defaultCat == 0){
/*********************
* Type you code here *
**********************/
}
});
Related
How to get iterated value of an object returned from XPATH request.
I have this HTML template:
<div class="item">
<span class="light">Date</span>
<a class="link" href="">2018</a>
(4pop)
</div>
<div class="item">
<span class="light">From</span>
<span>
<a class="link" href="" title="Bob" itemprop="url"><span itemprop="name">Bob</span></a>,
</span>
<span>
<a class="link" href="" title="Peter" itemprop="url"><span itemprop="name">Peter</span></a>
</span>
</div>
<div class="item">
<span class="light">For</span>
<a class="link" href="">Bak</a>,
<a class="link" href="">Cam</a>,
<a class="link" href="">Oli</a>
</div>
<div class="item">
<span class="light">Nat</span>
<a class="link" href="">Cool</a>
</div>
</div>
And my Javascript code:
var doc = new DOMParser().parseFromString(HTMLContent,'text/html');
var infos = doc.evaluate('//div[#class="item"]/span[1]', doc, null, XPathResult.ANY_TYPE, null);
var nodes = [];
for(var node = infos.iterateNext(); node; node = infos.iterateNext()) {
nodes.push(node);
console.log(node.textContent);
// Until here, all things works well ! Except the code from here:
var nodde = node.nextElementSibling.attributes;
nodde.forEach(function(item){
console.log(item);
});
}
My goal is to get the respective value for each categorie, for example:
Date = 2018, (4pop)
From = Bob, Peter
For = Bak, Cam, Oli
Nat = Cool
I tried to iterate: node.nextElementSibling.attributes but without any success !
What i have tried:
var nodde = node.nextElementSibling.attributes;
nodde.forEach(function(item){
console.log(item);
});
You can check it on the Javascript code, but unfortunatelly This will give null result.
Is there a way to get the expected result please ?
Once you get an item you can iterate through childNodes which include tags and texts.
var items = document.evaluate('//div[#class="item"]', doc, null, XPathResult.ANY_TYPE, null);
while (item = items.iterateNext()) {
var values = [];
var nodes = item.childNodes;
for (var i = 2; i < nodes.length; i++) {
var value = nodes[i].textContent.trim().replace(',', '');
if (value.length) values.push(value);
}
console.log(item.getElementsByClassName('light')[0].innerText + " = " + values.join(', '));
}
Prints:
Date = 2018, (4pop)
From = Bob, Peter
For = Bak, Cam, Oli
Nat = Cool
<ul>
<li>
<div class="link" id="contentLink20000002">
Link 1
</div>
</li>
<li>
<div class="link" id="contentLink1000002">
Link 2
</div>
</li>
<li>
<div class="link" id="contentLink2000003">
Link 3
</div>
</li>
<li>
<div class="link" id="contentLink2000004">
Link 4
</div>
</li>
</ul>
I have this structure an I am trying to separate id's which starts with 'contentLink2'. I have tried achieving this with .contains and regex but no luck so far.
var listids = $('ul li div');
listids.each(function(li){
var contentId = $(this).filter('contentLink2').attr('id');
console.log(contentId);
});
What i am trying is to create navigation. Like
Text
link1
link2
Text
link3
link4
HTML is dynamic so I don't have control it.
just use the attr to get to the id
var listids = $('div.link');
listids.each(function(index, element){
var contentId = $(this).attr('id');
// or use the second paramater to access the element
// var contentId = $(element).attr('id');
console.log(contentId.indexOf('contentLink2') !== -1);
});
Can do this with a jQuery attribute selector
listids.filter('[id^=contentLink2]').doSomething()
use JS instead
var x = document.getElementsByTagName('DIV');
for(i = 0 ; i < x.length ; i++){
var y = document.getElementsByTagName('DIV')[i];
var z = y.getAttribute('ID');
var m = z.search('contentLink2');
if(m == -1){
// NO THING
}else{
// Do Some Thing Here
};
}
I guess this what you are looking for.
The following code works, but I think there's room for improvement. The index check is there because after the first element is removed the next element looks like it has an index of -1, but is actually the previously removed element. Then it iterates again and finds the clicked element and removes it. BUT since the index is -1 on the first go around the wrong group gets deleted.
How do I keep the zombie elements from being iterated on more efficiently? This is in a backbone view with an in page confirmation.Thanks.
EDIT: To add HTML
Group section always has a default group that shouldn't be deleted.
<div class="section-border-top--grey js-favorite-group">
<h4 class="expandable__cta cta--std-teal js-expand-trigger"><span class="icon icon-plus--teal expandable__cta-icon"></span>All Doctors</h4>
<div class="expandable__content js-favorite-doctor-row-container" aria-expanded="true">
<div class="location-section dr-profile">
<div class="section__content js-doctor-row">
<div class="favorite-doctor-manage__row">
DR info
</div>
</div><!--/section__content-->
</div><!--/location-section-->
</div><!--/expandable__content-->
Tag section to remove groups
<div class="js-favorite-doctor-manage-add-remove">
<div class="grid-construct">
<div class="expandable" data-controller="expandable">
<ul class="tag-list js-group-list" tabindex="-1">
<li class="tag tag--teal" >
Lauren's Doctors
<ul class="tag-sub">
<li><button class="tag-icon tag-icon--close-white js-group-remove">Remove group: Lauren's Doctors</button></li>
</ul>
</li>
<li class="tag tag--teal" >
Timmy's Doctors
<ul class="tag-sub">
<li><button class="tag-icon tag-icon--close-white js-group-remove">Remove group: Timmy's Doctors</button></li>
</ul>
</li>
</ul>
</div>
removeGroup: function( evt ) {
var deleteGroup = function() {
if ( $(evt.currentTarget).closest('.tag').hasClass('is-active')){
var clickedTag = $(evt.currentTarget).closest('.tag');
var groupList = this.$el.find('.js-group-list');
var groupTags = groupList.find('.tag');
var index = groupTags.index(clickedTag);
var groupSections = $('.js-favorite-group');
// add one to account for "All" section which is never removed
var groupToRemove = groupSections.eq(index + 1);
console.log(groupToRemove);
var removedGroupName = this.getGroupNameForSection(groupToRemove);
var allDoctors = groupSections.eq(0);
var allDoctorsContainer = allDoctors.find('.js-favorite-doctor-row-container');
if ( index > -1 ){
groupToRemove.find('.js-favorite-doctor-row').appendTo(allDoctorsContainer);
clickedTag.remove();
groupToRemove.remove();
this.updateSectionDropdowns();
this.ariaAlert('Group ' + removedGroupName + ' removed');
this.hideConfirm(evt);
}
}
};
this.showAlert(evt, deleteGroup);
},
showAlert: function (evt, callback) {
that = this;
var clickedTag = '';
clickedTag = $(evt.currentTarget).closest('.tag');
clickedTag.addClass('is-active').attr('data-delete','true');
$('.delete-acct-message').show().focus();
$('.js-remove-yes').on('click', function(evt){
evt.preventDefault();
callback.apply(that);
});
$('.js-remove-no').on('click', function(evt){
evt.preventDefault();
this.hideConfirm(evt);
});
},
I would suggest that you should use custom attributes in your html, this will simplify your javascript logic and make it more effective and efficient.
I have modified your html and javascript to add the support for custom attribute data-doc-group. Have a look at your group sections div here
<div data-doc-group="lauren" class="section-border-top--grey js-favorite-group">
<h4 class="expandable__cta cta--std-teal js-expand-trigger"><span class="icon icon-plus--teal expandable__cta-icon"></span>Lauren's Doctors</h4>
<div class="expandable__content js-favorite-doctor-row-container" aria-expanded="true">
<div class="location-section dr-profile">
<div class="section__content js-doctor-row">
<div class="favorite-doctor-manage__row">
DR info
</div>
</div><!--/section__content-->
</div><!--/location-section-->
</div>
Here are the tags with custom attributes
<li data-doc-group="lauren" class="tag tag--teal">
Lauren's Doctors
<ul class="tag-sub">
<li><button class="tag-icon tag-icon--close-white js-group-remove">Remove group: Lauren's Doctors</button></li>
</ul>
</li>
<li data-doc-group="timmy" class="tag tag--teal">
Timmy's Doctors
<ul class="tag-sub">
<li><button class="tag-icon tag-icon--close-white js-group-remove">Remove group: Timmy's Doctors</button></li>
</ul>
</li>
Here is the javascript to handle this, (this may be a bit buggy, but will give you a general idea)
removeGroup: function(evt) {
this.showAlert(evt, function() {
var $clickedTag = $(evt.currentTarget).closest('.tag'),
dataGroupName,
$groupToRemove,
removedGroupName,
$allDoctors = $('.js-favorite-group').eq(0),
$allDoctorsContainer = $allDoctors.find('.js-favorite-doctor-row-container');
if ($clickedTag.hasClass('is-active')){
dataGroupName = $clickedTag.data('doc-group');
$groupToRemove = $allDoctors.siblings('[data-doc-group="' + docGroupName + '"]');
if ($groupToRemove.length > 0){
$groupToRemove.find('.js-favorite-doctor-row').appendTo($allDoctorsContainer);
$clickedTag.remove();
$groupToRemove.remove();
removedGroupName = this.getGroupNameForSection($groupToRemove);
this.updateSectionDropdowns();
this.ariaAlert('Group ' + removedGroupName + ' removed');
this.hideConfirm(evt);
}
}
});
}
This may already been answred; however, I could not locate a particular solution.
Let's say I have following divs...
<div class="listings-area">
<div itemtype="http://schema.org/Product" itemscope="">
<a class="listing" data-id="D_2781467">blah blah </a>
some more blahj blah text here
</div>
<div itemtype="http://schema.org/Product" itemscope="">
<a class="listing" data-id="D_2781445">blah blah </a>
some more blahj blah text here
</div>
.......................
.......................
</div>
What I want is that I want to get all these data-id attributes and add to an array and then pass along in javascript cookie
If I do something like
$('a.listing').attr('data-id')
I get the data id of first element. I want all the element data id and then those ids added to an array...?
You can use .map():
var idArr = $('a.listing').map(function() {
return $(this).attr('data-id');
}).get();
then store it inside cookies using:
$.cookie("example", idArr);
if you're using jQuery cookie plugin.
You should use .data() to get data attribute:
$('a.listing').data('id');
to get all of them, use .each():
var arr = $.cookie('somecookiename').split(', '); // split string to array
$('a.listing').each( function(){
arr[i] = $(this).data('id') // convert string array entries to dataids
});
var yourarray = new Array();
var elements = document.getElementsByClassName('listing');
for ( var i = 0; i < elements.length; i++ )
{
var el = elements[i];
var id = jQuery(el).attr('data-id');
yourarray.push( id );
}
alert(yourarray);
Use .map() and .data() as shown here http://jsfiddle.net/iamnotsam/AExsP/
// Gets array of ids
var ids = $('.listing').map(function() {
return $(this).data('id');
}).get();
Other way of doing is using for loop..
Demo :
<div itemtype="http://schema.org/Product" itemscope="" class="ListingS">
<ul>
<li>
<a class="listing" data-id="D_2781467">blah blah </a>
<p>some more blahj blah text here </p>
</li>
<li>
<a class="listing" data-id="D_2781445">blah blah </a>
<p>some more blahj blah text here </p>
</li>
</ul>
</div>
<script>
$(function(){
var liLength = $('.ListingS').find('a').length;
var liDom = $('.ListingS').find('a');
for (var i = 0; i < liLength; i++ ) {
console.log( "try " + i + liDom.eq(i).attr('data-id'));
}
})
Below is the HTML that I have
<ul id="QBS">
<li>
<a class="qb_mode starting Rodgers" href="#">See Stats</a>
</li>
<li>
<a class="qb_mode Manning" href="#">See Stats</a>
</li>
<li>
<a class="qb_mode Brady" href="#">See Stats</a>
</li>
</ul>
I want to find this unordered list, then tell which item has the starting qb class and then return the class that has their name (brady rodger manning) etc.
What's throwing me in a loop is the fact that the link is wrapped in the list element.
Here is what I am trying:
element = $("#qbs"); // pretty sure I want this vs getElementbyDocumentID
children = element.children();` // gets me all the list elements
for (i=0;i<children.length;i++) {
grandchild = children[i].children();
???? How would I get the 3rd class on this element?
}
Sorry about the formatting.
How about this?
var allClasses = $("#QBS").find('li a[class^="qb_"]')
.map(function () {
return this.className.split(" ").pop();
}).get();
console.log(allClasses);
Fiddle
Provided the class started with qb_* is at the beginning and you want to take only the last class of the match.
if all your class names are qb_mode then:
var allClasses = $("#QBS").find('.qb_mode').map(function () {
return this.className.split(" ").pop();
}).get();
if you want all of them then:
var allClasses = $("#QBS").find('.qb_mode').map(function () {
var cls = this.className.replace(/qb_mode/,'');
return cls.trim().split(/\W+/);
}).get();
console.log(allClasses);
Fiddle
If I understood you correctly, how about:
var name = $('#QBS a.qb_mode.starting').prop('class').replace(/\s*(qb_mode|starting)\s*/g,'');
console.log(name); // Rogers
See demo here.
a=document.getElementById('QBS');
var b=a.getElementsByClassName("qb_mode");
var i, j=b.length, result=[];
for(i=0;i<j;i++) {
c=b[i].className.split(" ");
result.push(c.pop());
}
return result;
fiddle http://jsfiddle.net/3Amt3/
var names=[];
$("#QBS > li a").each(function(i){
var a=$(this).attr("class").split(" ");
names[i]=a[(a.length-1)];
console.log("Name is " + names[i]);
});
or a more precise selector
$("#QBS > li a.qb_mode").each( ....