Prepending javaScript element with html snippet into another html node - javascript

I am trying to insert a html block of code before the previous one. I am using the prepend() method to insert into a list and it works I am inserting where I want but its only outputting the plain html code
HTML
<div class="comments-list">
<ul class="comment-list-ul" id="comment-list-ul">
<?php require_once INCLUDES . 'blog-box.php';?>
</ul>
</div>
js.
function insertInto (){
var block = '<li class="comment-holder" id="_1"> ' +
'<div class="user-text"> ' +
'<h3 class="comment-username"></h3> ' +
'</div> ' +
'<div class="comment-body"> '+
'<div class="comment-text"></div> '+
'</div> '+
'<div class="comment-buttons"> '+
'<ul><li class="deleteBtn">Delete</li></ul> '+
'</div> '+
'</li> ';
$('comment-list-ul').prepend(block);
}
Output
<li class="comment-holder" id="_1"> <div class="user-text"> <h3 class="username-field"></h3> </div> <div class="comment-body"> <div class="comment-text"></div> </div> <div class="comment-buttons-holder"> <ul><li class="delete-btn">Delete</li></ul> </div> </li>
What am I doing wrong?

Related

Javascript onclick problem with multiple parameters

I am trying to pass multiple parameters in a 'onclick' but it is not working and JS gave me headaches.
When clicking the 'div' and going to agregarADetalleMenu gives me this error:
SyntaxError: missing ) after argument list
function LlenarTableMenu(data) {
$('#cards-productos').empty();
$.each(data, function(i, val) {
var block2 = '<div class="col-4 col-md-6" onclick="agregarADetalleMenu(' + val.id + ', ' + val.name + ', ' + val.price + ')">' +
'<figure class="card card-product"> ' +
'<div class="img-wrap">' +
' <img src="' + val.imagen + '">' +
#* '<center><a class="btn-overlay" href="#"><i class="fa fa-plus-circle"></i> AGREGAR </a></center>' + *# '</div>' +
'<figcaption class="info-wrap">' +
'' + val.name + '' +
'<div class="action-wrap"> ' +
'<div class="price-wrap h5">' +
#* '<span class="price-new">' + val.price.toFixed(2) + '</span>' + *# '<span style="display: none;" class="catid">' + val.id + '</span>' +
'</div>' +
'</div>' +
'</figcaption> ' +
'</figure> ' +
'</div>';
$("#cards-productos").append(block2);
});
}
Do you mean this?
Note I wrapped the function values in quotes - you nested your quotes
function LlenarTableMenu(data) {
$('#cards-productos').html(
data.map(val => `<div class="col-4 col-md-6" onclick="agregarADetalleMenu('${val.id}','${val.name}',${val.price})">
<figure class="card card-product">
<div class="img-wrap">
<img src="${val.imagen}">
<center><a class="btn-overlay" href="#"><i class="fa fa-plus-circle"></i> AGREGAR </a></center>
</div>
<figcaption class="info-wrap">
${val.name}
<div class="action-wrap">
<div class="price-wrap h5">
<span class="price-new">${val.price.toFixed(2)}</span>
<span style="display: none;" class="catid">${val.id}</span>
</div>
</div>
</figcaption>
</figure>
</div>`).join("")
);
}
This is better
function LlenarTableMenu(data) {
$('#cards-productos').html(
data.map(val => `<div class="agregar col-4 col-md-6" data-id="${val.id}" data-name="${val.name}" data-price="${val.price}">
<figure class="card card-product">
<div class="img-wrap">
<img src="${val.imagen}">
<center><a class="btn-overlay" href="#"><i class="fa fa-plus-circle"></i> AGREGAR </a></center>
</div>
<figcaption class="info-wrap">
${val.name}
<div class="action-wrap">
<div class="price-wrap h5">
<span class="price-new">${val.price.toFixed(2)}</span>
<span style="display: none;" class="catid">${val.id}</span>
</div>
</div>
</figcaption>
</figure>
</div>`).join("")
);
}
and then have
$('#cards-productos').on("click",".agregar",function() {
agregarADetalleMenu(this.dataset.id,this.dataset.val,this.dataset.price)
})
You're missing quotes around the values being passed in to the function. Because you already used single and double quotes in your string, you can use escaped single (or double) quotes as follows:
onclick="agregarADetalleMenu(\'' + val.id + '\', \'' + val.name + '\', \'' + val.price + '\')"

How to create if statement inside embedded HTML in JavaScript to show CSS class

How to display one of two classes based on if there is data in the js array.
e.g. if there is responseData.title show class grey else class white
I am trying this now:
let resultHTML = '<article class="item">\
<div class="post-main">\
<header class="clear">\
<a href="' + responseData.url + '"</a>\
<span class="post-date">just now</span>\
</header>\
'if (responseData.title) {
'<section class="grey">'
} else {
'<section class="white">'
}'\
' + articleImage + '\
<h3>' + responseData.title + '</h3>\
<div class="post-about">' + responseData.about + '</div>\
</section>\
</div>\
</article>';
You can use the ternary operator.
In your case, it would be like this:
let resultHTML = '<article class="item">\
<div class="post-main">\
<header class="clear">\
<a href="' + responseData.url + '"</a>\
<span class="post-date">just now</span>\
</header>\
' + responseData.title ?
'<section class="grey">'
:
'<section class="white">'
+ '\
' + articleImage + '\
<h3>' + responseData.title + '</h3>\
<div class="post-about">' + responseData.about + '</div>\
</section>\
</div>\
</article>';
I will prefer using Template literals (Template strings) with Conditional (ternary) operator which is more cleaner.
Demo:
let responseData = {title:'abc'}
let articleImage = 'test';
let resultHTML = `<article class="item">
<div class="post-main">
<header class="clear">
<a href=responseData.url </a>
<span class="post-date">just now</span>
</header>
${
responseData.title ?
'<section class="grey">'
: '<section class="white">'
}
${articleImage}
<h3> ${responseData.title} </h3>
<div class="post-about"> ${responseData.about} </div>
</section>
</div>
</article>`;
console.log(resultHTML);

How to get <a href anchor title from the first <span>...</span> only?

I have a html string that want to get a anchor title from the first span ONLY but my current code gives me the text for both span(file name and file size span).Could you guys help me get the title from the first span only(file name span)?Thanks.
https://jsfiddle.net/un3b55m6/
var htmlString = '<ul class="training-files">'+
' <li role="display">'+
' <a target="_blank" href="/request/a/b/c/d/123456" role="link" class="class-file clean la" item-la-action="click" item-la-label="tab-trainings-item" item-la-value="123456">'+
' <span class="file-name">Training_new_season_123456.zip</span>'+
' <span class="file-size">(20.5MB)</span>'+
' </a>'+
' </li>'+
' <li role="display">'+
' <a target="_blank" href="/request/a/b/c/d/123457" role="link" class="class-file clean la" item-la-action="click" item-la-label="tab-trainings-item" item-la-value="123457">'+
' <span class="file-name">Training_new_season_123457.zip</span>'+
' <span class="file-size">(10.2KB)</span>'+
' </a>'+
' </li>'+
'</ul>';
$($.parseHTML(htmlString)).each(function() {
$(this).find("a").each(function() {
var parent = $(this).parent();
alert("url:"+parent.find("a").attr("href")+" =>filename:"+parent.find("a").text());
});
});
Here is the fix
var htmlString = '<ul class="training-files">'+
' <li role="display">'+
' <a target="_blank" href="/request/a/b/c/d/123456" role="link" class="class-file clean la" item-la-action="click" item-la-label="tab-trainings-item" item-la-value="123456">'+
' <span class="file-name">Training_new_season_123456.zip</span>'+
' <span class="file-size">(20.5MB)</span>'+
' </a>'+
' </li>'+
' <li role="display">'+
' <a target="_blank" href="/request/a/b/c/d/123457" role="link" class="class-file clean la" item-la-action="click" item-la-label="tab-trainings-item" item-la-value="123457">'+
' <span class="file-name">Training_new_season_123457.zip</span>'+
' <span class="file-size">(10.2KB)</span>'+
' </a>'+
' </li>'+
'</ul>';
$($.parseHTML(htmlString)).each(function() {
$(this).find("a").each(function() {
var parent = $(this).parent();
alert("url:"+parent.find("a").attr("href")+"=>filename:"+parent.find(".file-name").text());});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can find the span elements in the anchor tag and get the first one like this
let firstSpanText = $(this).find('span').first().text();
console.log(firstSpanText);
see the compelete example below
var htmlString = '<ul class="training-files">'+
' <li role="display">'+
' <a target="_blank" href="/request/a/b/c/d/123456" role="link" class="class-file clean la" item-la-action="click" item-la-label="tab-trainings-item" item-la-value="123456">'+
' <span class="file-name">Training_new_season_123456.zip</span>'+
' <span class="file-size">(20.5MB)</span>'+
' </a>'+
' </li>'+
' <li role="display">'+
' <a target="_blank" href="/request/a/b/c/d/123457" role="link" class="class-file clean la" item-la-action="click" item-la-label="tab-trainings-item" item-la-value="123457">'+
' <span class="file-name">Training_new_season_123457.zip</span>'+
' <span class="file-size">(10.2KB)</span>'+
' </a>'+
' </li>'+
'</ul>';
$($.parseHTML(htmlString)).each(function() {
$(this).find("a").each(function() {
var parent = $(this).parent();
let firstSpanText = $(this).find('span').first().text();
console.log(firstSpanText);
alert("url:"+parent.find("a").attr("href")+" =>filename:"+firstSpanText);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Materialize Collapsible Dont Open with Javascript

I'm inserting Collapsible into HTML as soon as it receives JSON and adds the information to it.
But Collapsible does not open,
It only opens if I insert the same in HTML itself, but I can not leave it as I have to generate the results from JSON and thus create the Collapsibles for each object.
JAVASCRIPT:
function GeneratePeoples__(objJSON){
for(cat in objJSON.categories){
document.getElementById('peoples-information').innerHTML +=
'<ul class="collapsible" data-collapsible="accordion">' +
'<li>' +
'<div class="collapsible-header"><i class="fa fa-id-card-o" aria-hidden="true"></i><strong>People ('+ cat +')</strong></div>' +
'<div class="collapsible-body white">' +
'<ul class="collection">' +
'<li class="collection-item avatar">' +
'<i class="fa fa-male circle blue" aria-hidden="true"></i>' +
'<span class="title title-collection-content-information">Type of Categories</span>' +
'<p><strong>'+ objJSON.categories[cat].name +'</strong></p>' +
'<a href="#!" class="secondary-content">' +
'<span class="new black badge" data-badge-caption=" "><strong>+ objJSON.categories[cat].score + '%' +</strong></span>' +
'<span class="new black badge" data-badge-caption=" "><strong>Score</strong></span>' +
'</a>' +
'</li>' +
'</ul>' +
'</div>' +
'</li>' +
'</ul>';
}
};
HTML
<div id="peoples-information"></div>
WORKING:
function GenerateCelebrities__(objJSON){
for(cat in objJSON.categories){
for(cel in objJSON.categories[cat].detail.celebrities){
document.getElementById('celebrities-information').innerHTML +=
'<ul class="collapsible" data-collapsible="accordion">' +
'<li>' +
'<div class="collapsible-header"><i class="fa fa-id-card-o" aria-hidden="true"></i><strong>Celebrity ('+ cap++ +')</strong></div>' +
'<div class="collapsible-body white">' +
'<ul class="collection">' +
'<li class="collection-item avatar">' +
'<i class="fa fa-star circle yellow-text myDiv" aria-hidden="true"></i>' +
'<span class="title title-collection-content-information">Celebrity Name</span>' +
'<p><strong>'+ objJSON.categories[cat].detail.celebrities[cel].name +'</strong></p>' +
'<a href="#!" class="secondary-content">' +
'<span class="new black badge" data-badge-caption=" "><strong>'+ objJSON.categories[cat].detail.celebrities[cel].confidence +" %" +'</strong></span>' +
'<span class="new black badge" data-badge-caption=" "><strong>Confidence</strong></span>' +
'</a>' +
'</li>' +
'</ul>' +
'</div>' +
'</li>' +
'</ul>';
}
}
$(document).ready(function(){
$('.collapsible').collapsible();
});
};

Why the Div element looks fine when copy pasted manually, but looks awful when appended with jquery append?

My page makes an AJAX call with and adds some data to a div. Then appends to a DIV with jquery append. It seems that the appended content doesn't follow the css properly. I checked the output with the help of alert and pasted the output manually to the page , it looks fine. What could be the problem?
Here is the code
var myDiv = '<div class="list-group-item" onclick="myhref(' + "docinfo.html" + ');">' +
'<div class="row" id="row">' +
'<div class="col-xs-3 col-sm-5"/>' +
'<img src="' + docDetails[25] + '" class="img-thumbnail" width="100" height="100">' +
'<p><b>&#8377 </b>' + docDetails[24] + '</p>' +
'<p><span class="glyphicon glyphicon-eye-open"></span>' + docDetails[2] + '<br></p>' +
'<p><span class="glyphicon glyphicon-thumbs-up"></span> ' + docDetails[13] + ' </p>' +
'</div>' +
'<div class="col-xs-8 col-sm-9">' +
'<ul class="list-group">' +
'<p><b>' + docDetails[22] + '</b></p>' +
'<p>' + docDetails[10] + ' <span class="glyphicon glyphicon-briefcase"></span>' + docDetails[17] + 'yrs </p>' +
'<p><strong>Location:</strong>' + docDetails[14] + '</p>' +
'<p>' + day + '<br>' +
'<span>' + time + '</span><br>' +
'<a onclick="stopprop(event);" href="book.html" class="btn btn-success btn-md" role="button" style="max-width: 100px; float: right;"><span> <span>Book</a><span><span></span></span>' +
'</ul>' +
'</div>' +
'</div>';
$("#searchfield").append(myDiv);
Output of myDiv when checked through alert function:
<div class="list-group-item" onclick="myhref(docinfo.html);"><div class="row" id="row"><div class="col-xs-3 col-sm-5"/><img src="500" class="img-thumbnail" width="100" height="100"><p><b>&#8377 </b>0</p><p><span class="glyphicon glyphicon-eye-open"></span>null<br></p><p><span class="glyphicon glyphicon-thumbs-up"></span> Shalimar Bagh </p></div><div class="col-xs-8 col-sm-9"><ul class="list-group"><p><b>null</b></p><p>4 <span class="glyphicon glyphicon-briefcase"></span>nullyrs </p><p><strong>Location:</strong>Kamlesh clinic</p><p>undefined<br><span>null</span><br><a onclick="stopprop(event);" href="book.html" class="btn btn-success btn-md" role="button" style="max-width: 100px; float: right;"><span> <span>Book</a><span><span></span></span></ul></div></div>
and CSS is of bootstrap
and here is the snippet of searchfiled
<div class="container-fluid" id ="searchfield">
</div>
this the result , when appended with jquery: http://imgur.com/LYE9alR
and this is when I manually pasted the output of myDiv in #searchfield :http://imgur.com/jrWtuyN
Why are you concatenating string with no variables and values. Just create the string like this
var myDiv='<div class="list-group-item" onclick="myhref('+"docinfo.html"+');"><div class="row" id="row"><div class="col-xs-3 col-sm-5"/><img src="'+docDetails[25]+'" class="img-thumbnail" width="100" height="100"><p><b>&#8377 </b>'+docDetails[24]+'</p><p><span class="glyphicon glyphicon-eye-open"></span>'+docDetails[2]+'<br></p><p><span class="glyphicon glyphicon-thumbs-up"></span> '+docDetails[13]+' </p></div><div class="col-xs-8 col-sm-9"><ul class="list-group"><p><b>'+docDetails[22]+'</b></p><p>'+docDetails[10]+' <span class="glyphicon glyphicon-briefcase"></span>'+docDetails[17]+'yrs </p><p><strong>Location:</strong>'+docDetails[14]+'</p><p>'+day+'<br><span>'+time+'</span><br><a onclick="stopprop(event);" href="book.html" class="btn btn-success btn-md" role="button" style="max-width: 100px; float: right;"><span> <span>Book</a><span><span></span></span></ul></div></div>';
$("#searchfield").append(myDiv);
Verify div appended correct location and css file loaded. Verify using browser Inspect element.

Categories