I have a little problem with my HTML template for convert to JSON. I wish convert a list of HTML messages to JSON. Thank you in advance for your response.
HTML Template
<div class="message">
<div class="message-data">
<div class="infos">
<h4 class="pseudo">Name</h4>
<span class="date">MM/DD/YYYY</span>
<span class="time">HH:MM</span>
</div>
</div>
<div class="message-content">
<div class="message-text">
Message here
</div>
</div>
</div>
<!-- Others .message -->
JSON Render
{
"list": [
{
"pseudo": "Name",
"date": "MM/DD/YYYY",
"time": "HH:MM",
"message": "Message here"
},
/* ... */
]
}
even if it doesn't look that cool I think this will be much faster:
var pseudo = document.getElementsByClassName("pseudo");
var date = document.getElementsByClassName("date");
var time = document.getElementsByClassName("time");
var message = document.getElementsByClassName("message-text");
var list = [];
for(var i=0, l=pseudo.length;i<l;i++) {
list.push({
pseudo: pseudo[i].textContent,
data: date[i].textContent,
time: time[i].textContent,
message: message[i].textContent
})
}
console.log(list);
.. depending on your file structure this may not be the best solution
You can use jQuery to simply extract your date from html:
var result = [];
$(".message").each(function() {
var obj = {
pseudo: $(this).find(".pseudo").text(),
date: $(this).find(".date").text(),
time: $(this).find(".time").text(),
message: $(this).find(".message-text").text(),
};
result.push(obj);
})
console.log(result)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message">
<div class="message-data">
<div class="infos">
<h4 class="pseudo">Name</h4>
<span class="date">MM/DD/YYYY</span>
<span class="time">HH:MM</span>
</div>
</div>
<div class="message-content">
<div class="message-text">
Message here
</div>
</div>
</div>
<div class="message">
<div class="message-data">
<div class="infos">
<h4 class="pseudo">John</h4>
<span class="date">09/11/2011</span>
<span class="time">HH:MM</span>
</div>
</div>
<div class="message-content">
<div class="message-text">
World Disaster
</div>
</div>
</div>
Simply get all your .message elements, and cycle through them to add their properties to the resulting Array (I used trim() to remove extra spaces at the beginning and the end of the message texts):
console.log( messagesToJSON() );
function messagesToJSON(){
var messages = [],
elements = $('.message');
for(var i=0; i<elements.length; i++){
messages.push({
"pseudo": elements.eq(i).find('.pseudo').text(),
"date": elements.eq(i).find('.date').text(),
"time": elements.eq(i).find('.time').text(),
"message": elements.eq(i).find('.message-text').text().trim()
});
}
return {list: messages};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message">
<div class="message-data">
<div class="infos">
<h4 class="pseudo">Kevin</h4>
<span class="date">08/01/2016</span>
<span class="time">14:52</span>
</div>
</div>
<div class="message-content">
<div class="message-text">
Hi there!
</div>
</div>
</div>
<div class="message">
<div class="message-data">
<div class="infos">
<h4 class="pseudo">Robert</h4>
<span class="date">08/01/2016</span>
<span class="time">15:03</span>
</div>
</div>
<div class="message-content">
<div class="message-text">
Hello
</div>
</div>
</div>
Related
I try to get text from a site, using javascript and textContent
i use this code
var markets=document.getElementsByClassName('sip-MarketGroup ')
for (var i=0;i<markets.length;i++){
try {
console.log(markets[i].textContent);
} catch (error) {
console.error(error);
}
}
a part of html into the site is this below
<div class="sip-MarketGroup">
<div class="sip-MarketGroupButton sip-MarketGroup_Open ">
<div class="sip-MarketGroupButton_Text " style="">Fulltime Result</div>
<div class="sip-MarketGroupButton_FavouriteButton sip-FavouriteButton ">
<div class="sip-FavouriteButton_SVG "> </div>
</div>
</div>
<div class="gl-MarketGroup_Wrapper ">
<div class="gl-MarketGroupContainer ">
<div class="gl-Market gl-Market_General gl-Market_General-topborder gl-Market_General-pwidth100 ">
<div class="gl-Participant gl-Participant_General gl-Market_General-cn3 ">
<span class="gl-Participant_Name">QPR</span>
<span class="gl-Participant_Odds">12.00</span>
</div>
<div class="gl-Participant gl-Participant_General gl-Market_General-cn3 ">
<span class="gl-Participant_Name">Draw</span>
<span class="gl-Participant_Odds">4.00</span>
</div>
<div class="gl-Participant gl-Participant_General gl-Market_General-cn3 ">
<span class="gl-Participant_Name">Bournemouth</span>
<span class="gl-Participant_Odds">1.36</span>
</div>
</div>
</div>
</div>
</div>
and i get
Fulltime ResultQPR12.00Draw4.00Bournemouth1.36
without spaces, how can i get this text but seperated with ";" like this
Fulltime Result;QPR 12.00;Draw 4.00;Bournemouth 1.36;
Why don't you use the method "innerText" instead?
And you can do the following:
var markets=document.getElementsByClassName('sip-MarketGroup ')
for (var i = 0; i < markets.length; i++) {
try {
console.log(markets[i].innerText.split('\n').join(';'));
} catch (error) {
console.error(error);
}
}
But you can always remove the .join(';') and just use the array to do whatever you need :) Maybe even string interpolation!
Give me a heads up if you liked my answer!
Happy New Year!
Pedro
json
[
{
"PROFILEUSERS_ID": "PTOKE000007",
"ALAMATUMKM": "Komp.Srijaya Abadi",
"dataTrouble": [
{
"NO": 1,
"IDMASALAH": "PTOmsl000001",
"IDNARASUMBER": "Marfua000100",
"IDUMKM": "PTOKE000007",
"NAMANARASUMBER": "Marfuah, S.SI, M.Kom",
"NAMAUMKMPMT": "PT OKE",
"GAMBARNARASUMBER": "4dwuwHmmHeCGuEv2LQqOmhXxvnoRTZTi08hqYz2C.jpeg",
"KETERANGANPMT": "kami ingin seminar/workshop pembahasan untuk AI di bidang pengelolaan ekonomi untuk mengetahui lebih lanjut peran AI,\r\nDan Belajar UI/UX\r\n\r\nTerima Kasih",
"TLPUMKM": "077845877",
"STATUSPMT": "WAIT",
"created_at": "2019-12-07 14:55:04",
"updated_at": "2019-12-07 14:59:22",
"listSkills": [
{
"NO": 1,
"IDMASALAHJP": "PTOmsl000001",
"JKMASALAH": "Artificial Intelligence",
"created_at": "2019-12-07 14:55:04",
"updated_at": null
},
{
"NO": 2,
"IDMASALAHJP": "PTOmsl000001",
"JKMASALAH": "UI/UX",
"created_at": "2019-12-07 14:55:04",
"updated_at": null
}
]
}
]
}
]
I already tried like this:
let content = ``;
data.forEach(item => {
item.dataTrouble.forEach(child => {
console.log(child);
let customDate = child.created_at;
let subsString = customDate.substring(0, 10);
let newDate = subsString.split("-").reverse().join("-");
content += `
<div class="panel panel-default panel-post">
<div class="panel-heading">
<div class="media">
<div class="media-left">
<a href="#">
<img src="http://localhost/Project_Web/laravel/project/Development/ppu-web/public/assetLogin/img/profile/${child.GAMBARNARASUMBER}" alt="Siostium Activity Image" />
</a>
</div>
<div class="media-body">
<h4 class="media-heading">
${child.NAMANARASUMBER}
</h4>
Tanggal Registrasi Acara: ${newDate}
</div>
</div>
</div>
<div class="panel-body">
<div class="post">
<div class="post-heading">
<p style="text-align: justify;">${child.KETERANGANPMT}</p>
</div>
<div class="post-content">
</div>
</div>
</div>
<div class="panel-footer">
<ul>
<li>
<a href="#">
<p>Permasalahan:</p>
<small><span class="label bg-red">${child.listSkills.JKMASALAH}</span></small>
</a>
</li>
<li></li>
<li></li>
</ul>
<div class="form-group">
<div class="form-line">
</div>
</div>
</div>
</div>
`
});
document.getElementById('activity').innerHTML = content;
});
But on the <small><span class="label bg-red">${child.listSkills.JKMASALAH}</span></small>,
the data is undefined.
I already tried to add looping after the child but the result of data are 3 not 2 data.
listSkills is an array you can access it through its index.
like: child.listSkills[index].JKMASALA.
you can map and show values like:
child.listSkills.map(obj => (
<small>
<span class="label bg-red">
{obj.JKMASALAH}
</span>
</small>
))
I have this code who simply create a array with html element and loop for parse the sort array.
$('document').ready(function(){
var arrElementStyle = [];
$('.bands-alphabetique [id*="band-style-"]').each(function(index){
var style = $(this).attr('id').split('-')[2];
arrElementStyle[style + '-' + index ] = $(this).find('.element');
});
arrElementStyle.sort();
$('.bands-alphabetique').hide();
for(style in arrElementStyle){
$('.large-centered.col-md-12.clearfix').append(arrElementStyle[style]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-centered col-md-12 clearfix">
<div class="bands-alphabetique">
<div class="col-md-3" id="band-style-rock">
<div class="element">
<h1 class="band-style-title">Rock</h1>
Fiction In Motion
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Pop</h1>
Marianas Trench
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Alternatif</h1>
Anberlin
</div>
</div>
</div>
</div>
When I parse the html the result is not sort?(I want sort by style of music) Why? Want should I do.
in your code you declared arrElementStyle as an array, but later you used it as an associative array for inserting data. So it is better to declare arrElementStyle as an object for this.
Here is an example demo of what I think you wanted to achieve with the help of sort() for sorting the objects keys:
$('document').ready(function() {
var arrElementStyle = {}; // declare arrEleemntStyle as object
$('.bands-alphabetique [id*="band-style-"]').each(function(index) {
var style = $(this).attr('id').split('-')[2];
// push into object of key <style>-<index> the elements
arrElementStyle[style + '-' + index] = $(this).find('.element');
});
// get the keys of arrElementStyle for sorting
var keys = Object.keys(arrElementStyle),
i, len = keys.length;
console.log('before = ', keys);
keys.sort(); // sort the object keys
console.log('after = ', keys);
$('.bands-alphabetique').hide();
// iterate the sorted keys and append it
for (i = 0; i < len; i++) {
var k = keys[i];
$('.large-centered.col-md-12.clearfix').append(arrElementStyle[k]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-centered col-md-12 clearfix">
<div class="bands-alphabetique">
<div class="col-md-3" id="band-style-rock">
<div class="element">
<h1 class="band-style-title">Rock</h1>
Fiction In Motion
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Pop</h1>
Marianas Trench
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Alternatif</h1>
Anberlin
</div>
</div>
</div>
</div>
Issue is you're trying to sort an object.. not an array. So let's use an object and sort it's keys.
$('document').ready(function() {
// here's the issue I was saying about
var elements = {};
$('.bands-alphabetique').hide().find('[id*="band-style-"]').each( function( index ) {
elements[ $(this).attr('id').split('-')[2] + '-' + index ] = $(this).find('.element');
});
var styles = Object.keys(elements);
styles.sort();
styles.forEach(function(style) {
$('.large-centered.col-md-12.clearfix').append(elements[style]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-centered col-md-12 clearfix">
<div class="bands-alphabetique">
<div class="col-md-3" id="band-style-rock">
<div class="element">
<h1 class="band-style-title">Rock</h1>
Fiction In Motion
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Alternatif</h1>
Anberlin
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Pop</h1>
Marianas Trench
</div>
</div>
</div>
</div>
The problem is that you're not sorting an array. You have an object with different properties (style + '-' + index).
In other words, associative array does not exists in Javascript. What you really had was an object arrElementStyle with many properties.
$('document').ready(function(){
var arrElementStyle = [];
$('.bands-alphabetique [id*="band-style-"]').each(function(index){
var style = $(this).attr('id').split('-')[2];
arrElementStyle[index] = $(this).find('.element');
arrElementStyle[index].bandStyle = $(this).find('.band-style-title')[0].innerHTML;
});
arrElementStyle.sort(function(elementA, elementB){
return elementA.bandStyle > elementB.bandStyle;
});
$('.bands-alphabetique').hide();
for(style in arrElementStyle){
$('.large-centered.col-md-12.clearfix').append(arrElementStyle[style]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-centered col-md-12 clearfix">
<div class="bands-alphabetique">
<div class="col-md-3" id="band-style-rock">
<div class="element">
<h1 class="band-style-title">Rock</h1>
Fiction In Motion
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Pop</h1>
Marianas Trench
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Alternatif</h1>
Anberlin
</div>
</div>
</div>
</div>
My code have divs of movies which are used to display movie with poster, now i want jquery to sort divs for me on basis of title,
<!-- Movie -->
<div class="movie" title="Reservoir Dogs">
<div class="movie-image">
<span class="play"><span class="name">Reservoir Dogs |
Reservoir Dogs</span></span><img src="http://ia.media-imdb.com/images/M/MV5BMTQxMTAwMDQ3Nl5BMl5BanBnXkFtZTcwODMwNTgzMQ##._V1_SX300.jpg" alt="movie">
</div>
<div class="rating">
<p>RATING</p>
<div class="stars">
<div class="stars-in4">
</div>
</div>
<span class="comments"></span>
</div>
</div>
<!-- end Movie -->
<!-- Movie -->
<div class="movie" title="Saw">
<div class="movie-image">
<span class="play"><span class="name">Saw |
Saw</span></span><img src="http://ia.media-imdb.com/images/M/MV5BMjAyNTcxNzYwMV5BMl5BanBnXkFtZTgwMzQzNzM5MjE#._V1_SX300.jpg" alt="movie">
</div>
<div class="rating">
<p>RATING</p>
<div class="stars">
<div class="stars-in4">
</div>
</div>
<span class="comments"></span>
</div>
</div>
<!-- end Movie -->
<!-- Movie -->
<div class="movie" title="Scarface">
<div class="movie-image">
<span class="play"><span class="name">Scarface |
Scarface</span></span><img src="http://ia.media-imdb.com/images/M/MV5BMjAzOTM4MzEwNl5BMl5BanBnXkFtZTgwMzU1OTc1MDE#._V1_SX300.jpg" alt="movie">
</div>
<div class="rating">
<p>RATING</p>
<div class="stars">
<div class="stars-in4">
</div>
</div>
<span class="comments"></span>
</div>
</div>
<!-- end Movie -->
<!-- Movie -->
<div class="movie" title="Signs">
<div class="movie-image">
<span class="play"><span class="name">Signs |
Signs</span></span><img src="http://ia.media-imdb.com/images/M/MV5BNDUwMDUyMDAyNF5BMl5BanBnXkFtZTYwMDQ3NzM3._V1_SX300.jpg" alt="movie">
</div>
<div class="rating">
<p>RATING</p>
<div class="stars">
<div class="stars-in3">
</div>
</div>
<span class="comments"></span>
</div>
</div>
<!-- end Movie -->
<!-- Movie -->
<div class="movie" title="Stir of Echoes">
<div class="movie-image">
<span class="play"><span class="name">Stir of Echoes |
Stir of Echoes</span></span><img src="http://ia.media-imdb.com/images/M/MV5BMTU0OTAyMDQzNV5BMl5BanBnXkFtZTcwNTg1NjYyMQ##._V1_SX300.jpg" alt="movie">
</div>
<div class="rating">
<p>RATING</p>
<div class="stars">
<div class="stars-in4">
</div>
</div>
<span class="comments"></span>
</div>
</div>
<!-- end Movie -->
Now here is my current code
$(document).ready(function () {
var desc = false;
document.getElementById("sort").onclick = function () {
sortUnorderedList("movie", desc);
desc = !desc;
return false;
}
});
function sortUnorderedList(ul, sortDescending) {
if (typeof ul == "string")
var lis = document.getElementsByClassName("movie");
var vals = [];
for (var i = 0, l = lis.length; i < l; i++)
vals.push(lis[i]);
debugger;
vals.sort(function (a, b) { return a.title - b.title });
//vals[].title.sort();
if (sortDescending)
vals.reverse();
for (var i = 0, l = lis.length; i < l; i++)
lis[i].innerHTML = vals[i].innerHTML;
}
above code is not giving desired result
can u suggest better way to do it
You can significantly simplify your code if you use more jQuery, anyway you are using it. Entire code in this case will be:
$(document).ready(function () {
var desc = false;
$("#sort").click(function () {
sortUnorderedList("movie", desc);
desc = !desc;
});
});
function sortUnorderedList(ul, sortDescending) {
$('.' + ul).sort(function(a, b) {
return sortDescending ? a.title.localeCompare(b.title) : b.title.localeCompare(a.title);
}).appendTo('body');
}
Just note that instead of appendTo('body'), you should append to appropriate container that holds .movie elements. I'm appending to body because this is a container for movie divs in my demo.
Demo: http://jsfiddle.net/212oc0kw/
I am trying to write a little jQuery script that checks a set of div's to see if they have a data-name attribute. For the ones that have a data-name, it will create a link. The href of that link should be the name of the data-value plus contain the file extension (eg. .txt).
Everything seems to work OK except when I try to add the data value onto the link. The ultimate result of this script is to output something like this for each of those div's:
<p class="data-link">Edit
Below is my script. I have identified that area that I am having issue with.
var dataNameWrappers = $("div#desktopSidebar div[data-name]");
dataNameWrappers.each(function() {
var dataNameWrappers_action = "" + $(this).attr("data-name");
$(this).prepend("<p class='edit-link'><a>Edit</a></p>");
var dataNameWrapperEditLink = $("div#desktopSidebar p.edit-link a");
dataNameWrapperEditLink.each(function() {
$(this).attr('href', <<stuck_here>>);
});
});
Any help will be great.
Thanks
As requested, here is my sidebar HTMl structure
<div id="desktopSidebar">
<div class="sidebar userbox">
<h3 class="sidebarheader"> Welcome {{username}}}</h3>
</div>
<div data-name="social_media_sitewide" class="sidebar socialmedia">
<h3 class="sidebarheader">Follow Tennis-Chat</h3>
</div>
<div data-name="site_promotions" class="sidebar promotions">
<h3 class="sidebarheader">Current Promotions</h3>
</div>
<div data-name="livescores" class="sidebar Livescores">
<h3 class="sidebarheader">Live Scores</h3>
</div>
<div class="sidebar tournaments">
<h3 class="sidebarheader">Tournaments</h3>
</div>
<div data-name="featured-profiles" class="sidebar profiles">
<h3 class="sidebarheader">Today's Profile: {{featured_profile_name}}</h3>
</div>
<div data-name="side_advertisment" class="sidebar Advertisement">
<h3 class="sidebarheader">Advertisement</h3>
</div>
<div class="sidebar Headlines">
<h3 class="sidebarheader">Tennis-Chat Headlines</h3>
</div>
<div class="sidebar mostrecent" id="mostRecentTopics">
<h3 class="sidebarheader">Most Recent Posts</h3>
</div>
</div>
I don't know why you are using a second loop to add the HREFs when you already have everything you need.
Working fiddle here: http://jsfiddle.net/Q4j8S/.
HTML:
<div id="desktopSidebar">
<div class="sidebar userbox">
<h3 class="sidebarheader"> Welcome {{username}}}</h3>
</div>
<div data-name="social_media_sitewide" class="sidebar socialmedia">
<h3 class="sidebarheader">Follow Tennis-Chat</h3>
</div>
<div data-name="site_promotions" class="sidebar promotions">
<h3 class="sidebarheader">Current Promotions</h3>
</div>
<div data-name="livescores" class="sidebar Livescores">
<h3 class="sidebarheader">Live Scores</h3>
</div>
<div class="sidebar tournaments">
<h3 class="sidebarheader">Tournaments</h3>
</div>
<div data-name="featured-profiles" class="sidebar profiles">
<h3 class="sidebarheader">Today's Profile: {{featured_profile_name}}</h3>
</div>
<div data-name="side_advertisment" class="sidebar Advertisement">
<h3 class="sidebarheader">Advertisement</h3>
</div>
<div class="sidebar Headlines">
<h3 class="sidebarheader">Tennis-Chat Headlines</h3>
</div>
<div class="sidebar mostrecent" id="mostRecentTopics">
<h3 class="sidebarheader">Most Recent Posts</h3>
</div>
</div>
JavaScript:
var dataNameWrappers = $("div#desktopSidebar div[data-name]");
dataNameWrappers.each(function() {
var dataNameWrappers_action = $(this).attr("data-name");
console.log('data-name ' + dataNameWrappers_action);
$(this).prepend('<p class="edit-link">Edit</p>');
/* Don't need this
var dataNameWrapperEditLink = $("div#desktopSidebar p.edit-link a");
dataNameWrapperEditLink.each(function() {
$(this).attr('href', dataNameWrappers_action);
});
*/
});
Instead of iterating through the a tags after you do the prepend, it may be better to make the HTML fragment with the desired href attribute.
Here is the code that accomplishes that:
$('#desktopSidebar .sidebar[data-name]').each(function(index, el){
var href = $(el).attr('data-name') + ".txt";
$(el).prepend('<p class="edit-link">Edit');
});