I am retrieving the value of html tag in a JavaScript function, but right now if I wanted to retrieve the data attribute value of html and pass it in a JavaScript variable.
How can I do it?
// create a UL element
var ul = $('<ul></ul>');
// add some LI elements
ul.append(
$('<li class="bear" data-type="panda">panda bear</li>'),
$('<li class="bear" data-type="koala">koala bear</li>'),
$('<li class="wallaby" data-type="kangaroo">kangaroo</li>')
);
// this won't work because our UL is not in the dom yet
console.log($('.bear').length); //=> 0
// let's just pick the bears in our UL using our UL as the context
var bears = $('.bear', ul);
console.log(bears); //=> [li.bear, li.bear]
// lets loop through and see data attributes
bears.each(function() {
console.log($(this).attr('data-type'));
});
//=> "panda"
//=> "koala"
I think the problem is you are not using string concatenation here
statusHtmlArr.push('<li class="loc-li" data-test="' + rowData.APPT_LOC_QUAL[k].LOCATION_CD + '" value="' + rowData.APPT_LOC_QUAL[k].LOCATION_CD + '"><a class="sub-detail" href="Javascript:void(0);">' + rowData.APPT_LOC_QUAL[k].LOCATION + '</a></li>');
You can do:
var locID = $("li.loc-li")[0].data("test");
In order to retrieve an attribute of an element, it's easy by using jQuery.
$('#selectorId').attr('attribute name')
or
$('.className').attr('attribute name')
Related
I basically just want to display each entry of local storage on a new line inside a list element.
Here is my JS:
if ( counter == 1 ){
var json = JSON.parse(localStorage.getItem( localStorage.key( i )))
var textm = 'Entry:'+json.Entry+'\n Exercise: '+json.Exercise+'\n Date:'+json.Date+'\n Start: ' +json.Start+'\n End: '+json.End+'\n Calories: '+json.Calories;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(textm));
ul.appendChild(li);
};
Very long i know, but this is the output I receive:
What is the reasoning for this? Do I not use line breaks right? or could it potentially be my CSS?
Unless you are using <pre> elements, or the equivalent CSS formatting, browsers treat newline characters as spaces, and condense multiple whitespace characters down to a single space. To have your fields appear on separate lines you need to insert <br> line break elements rather than newline characters. (Or use a nested list, or wrap each "line" in a <p> element, or whatever. But just using <br> elements is simplest.)
Except that because you are setting the text with .createTextNode() simply including "<br>" in your string would display those characters rather than creating an element. The simplest solution to this is to set the .innerHTML of your <li> element rather than using .createTextNode():
if (counter == 1) {
var json = JSON.parse(localStorage.getItem(localStorage.key(i)))
var textm = 'Entry:' + json.Entry + '<br> Exercise: ' + json.Exercise + '<br> Date:' + json.Date
+ '<br> Start: ' + json.Start + '<br> End: ' + json.End + '<br> Calories: ' + json.Calories;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.innerHTML = textm;
ul.appendChild(li);
}
As an aside, you don't need a semicolon after the closing } of an if block. Also, assuming the above code is contained in a loop, it would be more efficient to move the line with var ul = document.getElementById("list"); to before the loop, so that you only have to lookup that element once instead of doing it on every loop iteration.
In html as W3Schools says,for breaking line we must use <br> instead of \n(or any other character).
I hope this helps :)
Here is your soultion
You need to create element. you can't pass it as a string
Example : document.createElement("br");
if ( counter == 1 ){
var json = JSON.parse(localStorage.getItem( localStorage.key( i )))
var textm = 'Entry:'+json.Entry+document.createElement("br")+' Exercise: '+json.Exercise+'\n Date:'+json.Date+'\n Start: ' +json.Start+'\n End: '+json.End+'\n Calories: '+json.Calories;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(textm));
ul.appendChild(li);
};
Update your text concatenation with <br/> instead of \n like below.
var textm = 'Entry:'+json.Entry+'<br/> Exercise: '+json.Exercise+'<br/> Date:'+json.Date+'<br/> Start: ' +json.Start+'<br/> End: '+json.End+'<br/> Calories: '+json.Calories;
li.innerHTML = textm;
I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);
I have a JSON object that looks like this:
var content = '[{"title":"John Apple","lastname":"Apple"},
{"title":"Kumar Patel","lastname":"Patel"},
{"title":"Michaela Quinn","lastname":"Quinn"},
{"title":"Peyton Manning","lastname":"Manning"},
{"title":"John Doe","lastname":"Doe"},
{"title":"Jane Lee","lastname":"Lee"},
{"title":"Dan McMan","lastname":"McMan"},
{"title":"Yu Win","lastname":"Win"}]';
And I am trying to edit it with jQuery to display in my div tag with the id of content-view
here is my jquery:
$.each(content, function(t, l){
$('#view-content').appendTo('<div id = "' + l + '">' + t + '</div>');
});
For some reason on my jsFiddle, which is right here: http://jsfiddle.net/gAWTV/
It just comes up blank with the result. Does anyone have any ideas? I am stumped...
---EDIT---
What i would like to do is have everything output into its own div tags like this:
<div id="Apple">John Apple</div>
<div id="Patel">Kumar Patel</div>
<div id="Quinn">Michaela Quinn</div>
etc...
Your content is a string, not an array of objects.
You firstly need to store it as an array, so get rid of the single quotations marks.
var content = [{"title":"John Apple","lastname":"Apple"},
{"title":"Kumar Patel","lastname":"Patel"},
{"title":"Michaela Quinn","lastname":"Quinn"},
{"title":"Peyton Manning","lastname":"Manning"},
{"title":"John Doe","lastname":"Doe"},
{"title":"Jane Lee","lastname":"Lee"},
{"title":"Dan McMan","lastname":"McMan"},
{"title":"Yu Win","lastname":"Win"}];
Unless there is a reason you store it as a string? Then you need to parse it.
var content_object = JSON.parse(content);
Then you can run your code. However, I think you want to "stringify" your JSON. If that's the case you also need to swap t with l, because l is the object. Finally, you want to append, not appendTo. The latter appends the subject to the target you specify, not the other way round (so in your case appendTo appends #view-content to your div you've constructed, which doesn't work).
$.each(content, function(t, l){
$('#view-content').append('<div id = "' + t + '">' + JSON.stringify(l) + '</div>');
});
JSFiddle
Final comment, I would use document fragments to build your list instead of appending the new divs to an existing one in the each loop - that improves performance.
After OP edit:
Change the last snippet to:
$.each(content, function(t, l){
$('#view-content').append('<div id = "' + l.lastname + '">' + l.title + '</div>');
});
Updated JSFiddle
Try this:
var content = [{"title":"John Apple","lastname":"Apple"},
{"title":"Kumar Patel","lastname":"Patel"},
{"title":"Michaela Quinn","lastname":"Quinn"},
{"title":"Peyton Manning","lastname":"Manning"},
{"title":"John Doe","lastname":"Doe"},
{"title":"Jane Lee","lastname":"Lee"},
{"title":"Dan McMan","lastname":"McMan"},
{"title":"Yu Win","lastname":"Win"}];
$.each(content, function(t, l){
$('<div/>',{
id: l,
text:t }).appendTo('#view-content');
});
DEMO
If i have some basic html that is saved in a variable $html and I want to use an each (jQuery) statement on it before appending to the page and I want to look in this string for each instance of a class and ammend $html.
This is what I was thinking...
$('.flipper', $html).each(function(){
var frontContent = $(this).find('.front > .content');
var backContent = $(this).find('.back > .content');
$(this).append('<div class="background"><div class="content">' + frontContent.html() + '<div class="back">' + backContent.html() + '</div></div></div>');
console.log($html);
});
this doesnt run - i guess because i am trying to update an element on the page rather than one stored in a variable
can I still use the each ?
Cheers
Looks like $html is a string, not a dom element reference... in that case changes made to the elements in the loop will not be reflected in the original string.
Try something like
var html = '';
var $html = $(html);
$('.flipper', $html).each(function () {
var frontContent = $(this).find('.front > .content');
var backContent = $(this).find('.back > .content');
$(this).append('<div class="background"><div class="content">' + frontContent.html() + '<div class="back">' + backContent.html() + '</div></div></div>');
});
console.log($html[0].outerHTML);
Demo: Fiddle
Try this:
$($html).find('.flipper').each(....);
I need to add the value into the span using dom. But now i am using string manipulation. how to change this into the dom or append the value . i need to get the return value in html formate using dom.
Define layer.id as some text and this will get replace in all span element content
$.each($("span"),function(){
$(this).html(layer.id);
});
Thanks
You can append like following :
$('.ClassName').append('<p>Test</p>');
$('#id').after('<p>Test</p>');
$('#id').before('<p>Test</p>');
Try with this:
$("<li class='" + liClass + "'>" + preElement +
"<label for='" + layer.id + "'>" + layer.name + "</label>").appendTo('ul.class');
//----------^^^^^
// use the id
// or class of
//the specific ul
use appendTo() instead return and append it to your element.
(as i see you are returning li then append it to the ul)