I have a difficulty with mapping my my Json data. I would like to add data attr to each div with .name class. So as the result is like that:
<div class="name" data-key="sth"> sty</div>
Key can be got like that: ['streme'].key
here is my buggy JS:
function getExistingLinks() {
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
var names = data.map(function (i) {
return i['link'].name
});
var keys = data.map(function (i) {
return i['link'].key
});
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$('div').addClass("name");
// $('div').each( function(index) {
$('div')[index].data("key") = keys[index];
}
container.appendChild(div);
});
});
return false;
}
names.forEach(function(name,index) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
$(div).data("key") = keys[index];
});
You need to remove the quotes in the $() selector!
As per your comment, may be try doing like:
var i = 0;
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$('div').addClass("name");
$('div').data("key", keys[i]);
container.appendChild(div);
i++;
});
the preferred method is to only add to the DOM once, as adding to the DOM will cause a redraw on each.
psuedo code as not sure what name represents in your innerHTML:
var divs = [];
for (var i, len = names.length; i < len; i++) {
divs.push($(''+name+'').data("key", keys[i]));
}
$container.append(divs);
http://codepen.io/jsdev/pen/2866265243563efd79cf05a5b12202b3
try something like this
$('.name').data('key') //will give you sth
Related
I have a json which i'm trying to parse it using javascript. Iteration count and the pages getting appended to it are going to be dynamic.
Expected Result
Just like the above image i'm able to take dynamic iteration keys from the below mentioned json.
Iteration.json
{
"count":[
{
"iteration1":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
},
{
"iteration2":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
}
]
}
When i click on iteration it has to populate the corresponding pagenames for that particular iteration as shown in expected result image. But what i get actually is (refer the image below):
Please find the code that i tried:
var pagenamearray = [];
$.getJSON("iteration.json", function(json) {
var hits = json.count;
var iterations, tnname, iteration;
for (var k in hits) {
var value;
if (hits.hasOwnProperty(k)) {
value = hits[k];
var iteratearray = [];
for (var j in value) {
if (value.hasOwnProperty(j)) {
j;
var check = value[j];
for (var i in check) {
if (check.hasOwnProperty(i)) {
var test = check[i];
for (var t in test) {
if (test.hasOwnProperty(t)) {
var pagename = JSON.stringify(t)
var arr = []
if (pagename.includes("PageName")) {
//alert("Key is " +pagename + ", value is" + JSON.stringify(test[t]));
for (var it = 0; it < hits.length; it++) {
if ((Object.keys(hits[it])).includes(j)) {
var pagenamevalue = test[t];
arr[it] = [];
arr.push(pagenamevalue);
}
}
}
//alert(arr)
}
pagenamearray.push(arr);
}
}
}
}
var row = document.createElement('div');
row.setAttribute("class", "row");
row.setAttribute("id", j)
var gridWidth = document.createElement('div');
gridWidth.setAttribute("class", "col-lg-12");
var panelRoot = document.createElement('div');
panelRoot.setAttribute("class", "panel panel-default");
var panelHeading = document.createElement('div');
panelHeading.setAttribute("class", "panel-heading");
var heading3 = document.createElement('a');
heading3.setAttribute("class", "panel-title");
var icon = document.createElement('i');
icon.setAttribute("class", "fa fa-long-arrow-right fa-fw");
heading3.appendChild(icon);
heading3.innerHTML = j;
heading3.setAttribute("onclick", "doit('" + j + "');");
panelHeading.appendChild(heading3);
/* var panelBody=document.createElement('div');
panelBody.setAttribute("class","panel-body");
panelBody.setAttribute("id","panellinks");*/
panelRoot.appendChild(panelHeading);
// panelRoot.appendChild(panelBody)
gridWidth.appendChild(panelRoot);
row.appendChild(gridWidth);
document.getElementById("analysis").appendChild(row);
}
}
}
});
function doit(value) {
var ul = document.getElementById(value);
if (ul != undefined) {
$("#" + "expandlinks").remove();
$("#" + value + value).remove();
}
var accordion = document.getElementById(value);
var panelBody = document.createElement('div');
panelBody.setAttribute("class", "panel-body");
panelBody.setAttribute("id", "expandlinks")
var tablediv = document.createElement('div')
var tablelink = document.createElement('a');
tablediv.appendChild(tablelink);
var graphdiv = document.createElement('div')
var graphlink = document.createElement('a');
graphdiv.appendChild(graphlink);
var recommndiv = document.createElement('div');
var recommendlink = document.createElement('a');
recommndiv.appendChild(recommendlink)
//alert(pagenamearray.length)
tablelink.innerHTML = pagenamearray;
/*graphlink.innerHTML="Timeline View";
recommendlink.innerHTML="Recommendations";*/
panelBody.appendChild(tablediv);
panelBody.appendChild(recommndiv);
panelBody.appendChild(graphdiv);
accordion.appendChild(panelBody);
}
Any advise on how to achieve this would be of great help. Thanks in advance.
I think the problem is how you assign the pagenamearray to tablelink.innerHTML. This converts the array to a string, converting all elements in the array to a string too and separating them by a comma each. However, your pagenamearray contains some empty arrays too; these will convert to an empty string in the process, but will still have a comma before and after them.
In your example code above, the pagenamearray will end up with a value of [[[],"T01_Launch"],[[],"T02_Login"],[null,[],"T01_Launch"],[null,[],"T02_Login"]] - when converted to a String, this will result in ",T01_Launch,,T02_Login,,,T01_Launch,,,T02_Login". So instead of assigning it to the innerHTML value directly, you'll first have to filter out the empty arrays and null values.
I am trying to write jason data into separate divs with class .name and data-key za data attr. I have problem with data and getting the right index for that.
Here is my buggy attempt. Console.log writes all keys, but the last function doesn't give divs the data attr
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
var names = data.map(function (i) {
return i['link'].name
});
var keys = data.map(function (i) {
return i['link']['key']
});
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
container.appendChild(div);
});
$.each((".name"), function(index) {
$(this).data("key", keys[index]);
console.log(keys[index]);
});
please try with this updated code
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
var names = data.map(function (i) {
return i['link'].name
});
var keys = data.map(function (i) {
return i['link']['key']
});
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
container.appendChild(div);
});
$(".name").each(function(index) {
$(this).data("key", keys[index]);
console.log(keys[index]);
});
You missed a $ in ('.names') $.each try this,
$.each($(".name"), function(index) {
// ----^ use $ here
$(this).data("key", keys[index]);
console.log(keys[index]);
});
or simply,
$(".name").each(function(index) {
$(this).data("key", keys[index]);
console.log(keys[index]);
});
You can add key while adding element in container like,
var i=0;
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
$(div).data("key", keys[i]);// set data here
container.appendChild(div);
i++;
});
I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this?
$('.poshytip-trigger').each(function (index) {
var $this = $(this);
var data = $this.data();
var options = {};
if (data['class-name']) {
options.className = data['class-name'];
}
if (data['align-x']) {
options.alignX = data['align-x'];
}
if (data['align-y']) {
options.alignY = data['align-y'];
}
if (data['offset-y']) {
options.offsetY = data['offset-y'];
}
if (data['offset-x']) {
options.offsetX = data['offset-x'];
}
$this.poshytip(options);
});
I would use a for..in loop to read the data-* tags.. Also you don't need to camelcase as jQuery converts it to camelCase internally... Source code reference.
$('.poshytip-trigger').each(function (index) {
var $this = $(this);
var data = $this.data();
var options = {};
for (var keys in data) {
options[keys] = data[keys];
}
// For older versions of jQuery you can use $.camelCase function
for (var keys in data) {
options[$.camelCase(keys)] = data[keys];
}
});
DEMO
for jQuery 1.4.4,
$('.poshytip-trigger').each(function(index) {
var $this = $(this);
var data = $this.data();
var options = {};
for (var keys in data) {
options[camelCase(keys)] = data[keys];
}
});
//copied from http://james.padolsey.com/jquery/#v=git&fn=jQuery.camelCase
function camelCase(str) {
return str.replace(/^-ms-/, "ms-").replace(/-([a-z]|[0-9])/ig, function(all, letter) {
return (letter + "").toUpperCase();
});
}
DEMO for 1.4.4
Something like this - It does convert offset-x to offsetX:
http://jsfiddle.net/8C4rZ/1/
HTML:
<p data-test="sdsd" data-test2="4434"></p>
JavaScript:
$(document).ready(function() {
var options = {};
for (var key in $("p").data()) {
options[key] = $("p").data(key);
}
console.log(options);
});
But I think Daniel's approach is better, since he explicitly controls which attributes gets set. This will take all data- attributes.
var names = ["className", "alignY", ...];
$(names).each(function(ind, name){
var dataName = name.replace(/[A-Z]/, function(letter){
return letter.toLowerCase();
});
if(data[dataName]){
options[name] = data[dataName];
}
});
Does this work? Unlike the other answers, this piece of code both convert only explicitly set attributes and keeps the options-object attribute name camelCase.
Try using a for in loop.
var array = ['class-name', 'align-x', 'align-y', 'offset-y', 'offset-x'];
for (x in array) {
if(data[array[x]]) {
options[array[x]] = data[array[x]];
}
}
Update: In response to the OP's clarification, he could write something like this:
var Pair = function(hyphenated, camcelCased) {
this.hyphenated = hyphenated;
this.camelCased = camelCased;
}
var array = [
new Pair('class-name', 'ClassName'),
new Pair('align-x', 'alignX'),
new Pair('align-y', 'alignY'),
new Pair('offset-x', 'offsetX'),
new Pair('offset-y', 'offsetY')];
var i, optionNameHyphenated, optionNameCamelCased;
for(i = 0; i < array.length; i++) {
optionNameHyphenated = array[i]['hyphenated'];
optionNameCamelCased = array[i]['camelCased'];
if (data[optionNameHyphenated]);
options[optionNameCamelCased] = data[optionNameHyphenated];
}
How can I get the list of attributes of an HTML string using Javascript? Here's my code so far.
function traverse_test(){
var root=document.getElementById('arbre0').childNodes;
for(var i=0;i<root.length;i++){
var lis = root[i];
if (lis =='[object HTMLUListElement]') {
for (var member in lis) {
if (typeof lis[member] == "string") {
var assertion = lis[member];
var resultat = assertion.search(/..Bookmarks/);
if (resultat != -1) {
output.innerHTML+= lis[member];
// Here I'd like to have the list of lis[member] attributes
for(var attr in lis[member].attributes) {
output.innerHTML+=lis[member].attributes[attr].name + "=\""+ lis[member].attributes[attr].value + "\"";
}
break;
}
}
}
}
}
}
Use the Node.attributes property of a DOM element. Example:
var foo = document.getElementById('foo'),
attrs = foo.attributes,
i = attrs.length,
attr;
while (i--)
{
attr = attrs[i];
console.log(attr.name + '="' + attr.value + '"');
}
Demo: http://jsfiddle.net/mattball/j8AVq/
Seems like all these answers point to how to get an attr list from a node but the question asks for attrs from an HTML string. Here is my 2cents.
//turn your string into a node and get your html strings NamedNodeMap
var temp = document.createElement("div");
temp.innerHTML = "<div attr-1 attr-2 attr-3 attr-4></div>";
temp = temp.firstElementChild.attributes;
//put the attributes in a an array
var list = Object.keys(temp).map( function( index ) { return temp[ index ] } );
console.log( list );
If you know the attributes to get the value you can do:
var MyValue = document.getElementById("myimage").getAttribute("src")
In JavaScript to loop all attributes:
var el = document.getElementById("someId");
var arr = [];
for (var i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
arr.push(attrs.item(i).nodeName);
}
The above code was taken from this question
Jquery might be another option:
http://plugins.jquery.com/project/getAttributes
[].slice
.apply(document.querySelector('something').attributes)
.forEach(function(item){
console.log(item, item.name, item.value);
});
I have little problem with element childrens.
Heres some code to explain my question:
function check(element){
// I want to get custom attribute from element children.
// Children elements are always radio buttons
var temp = element. ?? .attr('temp');
return temp;
}
// element variable is the whole div here
<div id = "test">
<table>
<tr>
<td> <input type="radio" temp="somethinghere"/></td>
</tr>
</table>
</div>
Hope someone has ideas or even better.. solution.
I think you want something like this:
function check(element) {
var ret = [];
for (var i = 0; i < element.childNodes.length; i++) {
if (element.childNodes[i].type == 'radio') {
ret.push(element.childNodes[i].getAttribute('temp'));
}
}
return ret;
}
This will return an array containing all the temp attributes of the radio children of the element.
var temp = element.getAttribute('temp')
Or
var temp = element.temp = temp;
Or
var temp = element['temp'] = temp;
https://developer.mozilla.org/en/DOM/element.getAttribute
Edit: try:
var temp = '';
for (var i = 0; i < element.childNodes; i++)
temp += element.childNodes[i].getAttribute('temp');
return temp;
Is this what you're looking for?
To get an array of all the children of element :
element.childNodes;
To get an array of all input tags that are descendants of element :
element.getElementsByTagName("input")
Then loop through either of those arrays.
try this for the first child radio button
var temp = element.children(':radio:first').attr('temp');
of if you want all 'temp' attr from all child radio button do following:
var arrTemp = element.children(':radio').map(function(){
return $(this).attr('temp');
// or you can make it more detail like:
// return { ID: $(this).attr('id'), Temp: $(this).attr('temp') };
}).get();
UPDATE for table sample
var arrTemp = element.find(':radio').map(function(){
return $(this).attr('temp');
// or you can make it more detail like:
// return { ID: $(this).attr('id'), Temp: $(this).attr('temp') };
}).get();