Get values in array from XPATH in Javascript - javascript

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

Related

filter div from their id using jquery

<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.

jQuery How to select all nodes text in div

I have a div like this:
<div class="movie">
Date:
<span class="date"> June 12, 1987 </span>
Título:
<span class="title">
<a class="select_movie" href="#">
Predator
</a>
</span>
Director: <span class="director">John McTiernan</span>
Starring: <span class="starring">Arnold Schwarzenegger</span>
</div>
I want all the text nodes in <div class="movie">, after the click of a link .select_movie
$('.select_movie').click(function(){
..........
..........
});
at the end I need to retrieve the value of the nodes to be assigned to a variables, like this:
var date = June 12, 1987;
var title = Predator;
var director = John McTiernan;
var starring = Arnold Schwarzenegger;
Try this in order to get each of the values:
$('.select_movie').click(function(){
var movie = $(this).closest(".movie");
var date = $(movie).find(".date").text();
var title = $(movie).find(".title .select_movie").text();
var director = $(movie).find(".director").text();
var starring = $(movie).find(".starring").text();
});
Fiddle: http://jsfiddle.net/unwgeqce/1/
something like this for each var:
var date = $('.movie').find('.date').text();

How do I get the data attributes of divs and then passed along in cookie

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'));
}
})

How to get text from span->li->ul-> Element

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 *
**********************/
}
});

How can I go to the Next and Previous value in a json array?

I've been beating my head against the wall with this one for days now. I have a list of items that when clicked, will move that indivual item to a div. Based on which item is clicked, I'm trying to go the the Next and Previous items in my list (json).
I'm kind of new to this and I just can't quite get this to work no matter what I try.
Here is the jsfiddle code. Thanks!
HTML:
<audio id="audio-player" name="audio-player" src="" ></audio>
<a id="next-bt" href="#">
<div class="player-musicnav-ff-column3">
<ul class="musicnav-ff">
<li class="ff">NEXT</li>
</ul>
</div>
</a>
<a id="prev-bt" href="#">
<div class="player-musicnav-ff-column3">
<ul class="musicnav-ff">
<li class="ff">PREV</li>
</ul>
</div>
</a>
<br/>
<br/>
<div id="player-digital-title">
</div>
<br/>
<br/>
<a href="#" id='player-handwriting-title'></a>​​
Javascript an Jquery:
$(document).ready(function(){
var treeObj = {"root":[{"id":"1","trackName":"Whippin Post"},{"id":"2","trackName":"Sweet Caroline"},{"id":"3","trackName":"Tears in Heaven"},{"id":"4","trackName":"Ain't She Sweet"},{"id":"5","trackName":"Octopus' Garden"},{"id":"6","trackName":"Teen Spirit"},{"id":"7","trackName":"Knockin on Heaven's Door"}]};
var $ul = $("<ul></ul>");
$.each(treeObj.root,function(i,v) {
$ul.append(
$("<li></li>").append( $("<a></a>")
.attr({"href":v.id,"data-file":v.trackFile})
.html(v.trackName)
)
);
});
$("#player-handwriting-title").empty().append($ul);
$("#player-handwriting-title a").click(function() {
var name = $(this).html(),
filename = $(this).attr("data-file");
filename2 = "upload-form/upload/" + filename;
$('#player-digital-title').html($(this).html());
document.getElementById('audio-player').src = filename2;
$("#audio-player")[0].play();
return false;
});
var myID = 0;
$("#next-bt").click(function() {
document.getElementById('player-digital-title').innerHTML = treeObj.root[++myID].trackName ;
});
var mylease = 6;
$("#prev-bt").click(function() {
document.getElementById('player-digital-title').innerHTML = treeObj.root[--mylease].trackName ;
});
});
​
Added a fiddle
http://jsfiddle.net/kabichill/JzL97/
check out..Hope its wat u expected...
try something like
var myID = 0;
$("#next-bt").click(function() {
myID++;
if(myID > treeObj.root.length) { myID = 0; }
document.getElementById('player-digital-title').innerHTML = treeObj.root[++myID].trackName ;
});
var mylease = 6;
$("#prev-bt").click(function() {
myID--;
if(myID < 0) { myID = treeObj.root.length; }
document.getElementById('player-digital-title').innerHTML = treeObj.root[--mylease].trackName ;
});

Categories

Resources