comment reply system with catching specific id value - javascript

hi guys I have a blog post page and comment and reply system. Everything works fine except one thing:
When I try to add a reply to a comment, I am always replying to the first comment. I think my fault is I can't reach the specific comment id when I click. Here is my html and ajax code:
HTML CODE
<div class="card" style=" margin-bottom:30px;">
<div class="card-header">
<a class="h3">#Model.Header</a>
<br />
<br />
<div class="row">
<div class="col-md-12 col-xs-12 col-xl-12">
<p style="font-size:small">
<b>Kategori: </b> #Model.Category.CategoryName ,<b>Makale Sayısı :</b> #Model.Category.Articles.Count()
<b>Yorum Sayısı :</b> #Model.Comments.Count() <br />
<b>Yayımlanma Tarihi: </b> #String.Format("{0: d MMMM yyyy}", Model.Date) ,<b>Etiketler:</b><i class="fa fa-tags"></i> #Model.Tags.Count()
</p>
<p style="font-size:small;">
<img class="rounded-circle img-fluid" style="width:100px;height:100px;" src="#Model.User.Photo" alt="#Model.User.FullName" />
Posted by:
#Model.User.UserName
</p>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-xl-12">
<img id="articlephoto" style="width:100%; height:350px" class="rounded float-left" src="#Model.Photo" alt="Card image cap">
</div>
</div>
<div class="row" style="margin-top:20px">
<div class="col-md-12 col-xs-12 col-xl-12">
<p>#Html.Raw(Model.Paragraph)</p>
<p style="font-size:small">
<b>Etiketler:</b>
#foreach (var item in Model.Tags)
{
<span class="tag">#item.TagName,</span>
}
</p>
</div>
</div>
</div>
</div>
<h4>Comments</h4>
<hr />
#foreach (var item in Model.Comments.ToList())
{
<!-- Single Comment -->
<div class="media mb-4">
<img style="height:40px; width:40px;" class="d-flex mr-3 rounded-circle" src="#item.User.Photo" alt="#item.User.FullName">
<div class="media-body" style="width:400px;">
<h5 class="mt-0">#item.User.UserName</h5>
<p style="word-break:break-all">
#item.Paragraph
#if (Convert.ToInt32(Session["UserId"]) == item.UserId)
{
<a class="btn btn-danger" href="/Home/DeleteComment/#item.CommentId">
Delete
</a>
<a class="btn btn-warning replybutton" href="#replyform">
Reply
</a>
}
</p>
<p style="font-size:small"><b>Yorum Tarihi:</b>#String.Format("{0: d MMMM yyyy}", item.Date)</p>
<span id="astar" class=""> #item.CommentId</span>
#foreach (var reply in Model.ReplyComments.Where(x => x.CommentId == item.CommentId).ToList())
{
<div class="media mt-4">
<img style="height:40px; width:40px;" class="d-flex mr-3 rounded-circle" src="#item.User.Photo" alt="#item.User.FullName">
<div class="media-body">
<h5 class="mt-0">#reply.User.UserName</h5>
<p>#reply.Paragraph</p>
#if (Convert.ToInt32(Session["UserId"]) == item.UserId)
{
<a class="btn btn-danger" href="/Home/DeleteReply/#reply.ReplyCommentId">
Sil
</a>
}
</div>
</div>
}
</div>
</div>
<hr />
}
#if (Session["UserId"] != null)
{
<!-- Comments Form -->
<div id="commentform" class="card my-4">
<h5 class="card-header">Yorum Yap:</h5>
<div class="card-body">
<form>
<div class="form-group">
<textarea id="comment" typeof="text" class="form-control" rows="3"></textarea>
</div>
<button type="submit" id="send" class="btn btn-primary">Yorum Yap</button>
</form>
</div>
</div>
<div id="replyform" class="card my-4 d-none">
<h5 class="card-header">Cevap Yaz:</h5>
<div class="card-body">
<div class="form-group">
<textarea id="replytext" name="replytext" typeof="text" class="form-control" rows="3"></textarea>
</div>
<button type="submit" id="reply" name="reply" class="btn btn-primary">Cevap Yaz</button>
</div>
</div>
}
else
{
<div class="row" style="margin-bottom:30px;">
<div class="col-md-6">
<h3 class="alert- alert-heading">Yorum Yapabilmek İçin Üye Girişi Yapmalısınız.</h3>
</div>
</div>
}
AND my javascript ajax code
<script type="text/javascript">
$(document).ready(function () {
$("#reply").click(function (e) {
var r_comment = $("#replytext").val();
var r_commentid = parseInt($("#astar").html());
$.ajax({
url: '/Home/ReplyComment/',
data: { replycomment: r_comment, articleid:#Model.ArticleId, commentid: r_commentid },
type: 'POST',
dataType: 'json',
success: function (data) {
alert("Cevap gönderildi");
window.location.reload();
}
});
});
})
</script>
My problem is that I can't catch the specific comment id when I click the reply button. I am getting the comment id from <span id="astar" class=""> #item.CommentId</span>

"When I try to add a reply to a comment, I am always replying to the first comment. " - it's because all your comments have the same ID and jQuery selects the first matching element.
All comments need to have a unique ID. I don't know what language that loop is in but you need to increment the ID. So astar-1, astar-2, astar-3 etc...
Example;
$(document).ready(function(){
var valueBox = document.getElementById('value-box');
$('.reply').on('click', function(){
var comment = $(this).prev().attr('id');
valueBox.innerHTML += '<br />Reply to comment: ' + comment;
console.log(comment);
});
});
.comment::after {
display: table;
content: ' ';
clear: both;
}
span {
display: block;
float: left;
width: 45%;
}
.reply {
display: block;
float: right;
width: 45%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment">
<span id="comment-1">Yorum 1</span>
<div class="reply">Cevapla</div>
</div>
<div class="comment">
<span id="comment-2">Yorum 2</span>
<div class="reply">Cevapla</div>
</div>
<div class="comment">
<span id="comment-3">Yorum 3</span>
<div class="reply">Cevapla</div>
</div>
<div id="value-box">
</div>

Related

if the class is active, reinstate the other with jquery

I want to update the comments of a post. Let's say the user has 2 comments, when he clicks edit I want to close the window of the other comment. In short, how can I keep one as "textarea" and the other as "span"?
$(document).on('click','.update-comment',function(e){
$('.active').removeClass('active');
let obj = $(this).closest('.comments');
let text = obj.find('.comment-text').attr('data-text');
obj.find('.ms-3').addClass('active');
if($('.ms-3').hasClass('active')){
$(obj.find('.comment-text')).replaceWith('<textarea id="updateComment">'+text+'</textarea>');
}else {
$(obj.find('.comment-text')).replaceWith('<span class="comment-text" data-text='+text+'>'+text+'</span>');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex py-2 comments" data-id="1">
<div class="flex-shrink-0">
<img src="https://via.placeholder.com/50" alt="..."/>
</div>
<div class="ms-3">
<div class="fw-bold">Name-1
<button type="submit" class="update-comment" data-id="1">Edit</button>
</div>
<span class="comment-text" data-text="Comment Example - 1" data-id="1">Comment Example - 1</span>
</div>
</div>
<hr>
<div class="d-flex py-2 comments" data-id="2">
<div class="flex-shrink-0">
<img src="https://via.placeholder.com/100" alt="..."/>
</div>
<div class="ms-3">
<div class="fw-bold">Name-2
<button type="submit" class="update-comment" data-id="2">Edit</button>
</div>
<span class="comment-text" data-text="Comment Example - 2" data-id="2">Comment Example - 2</span>
</div>
</div>
<hr>
Not trivial
I changed the button to type=button
I then removed the duplicate IDs and instead gave both span and textarea the class of comment-text
Then I changed the data-attr to just the .text() OR .val() depending on the element being a textarea or a span
I also cached several objects
$(document).on('click', '.update-comment', function(e) {
$allMS3 = $('.ms-3').removeClass('active');
let $thisMS3 = $(this).closest('.ms-3')
.addClass('active');
$allMS3.each(function() {
const $commentText = $(this).find('.comment-text')
let text = $commentText.is("span") ? $commentText.text() : $commentText.val();
if ($(this).hasClass('active')) {
$commentText.replaceWith('<textarea class="comment-text">' + text + '</textarea>');
} else {
$commentText.replaceWith('<span class="comment-text">' + text + '</span>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex py-2 comments" data-id="1">
<div class="flex-shrink-0">
<img src="https://via.placeholder.com/50" alt="..." />
</div>
<div class="ms-3">
<div class="fw-bold">Name-1
<button type="button" class="update-comment" data-id="1">Edit</button>
</div>
<span class="comment-text" data-text="Comment Example - 1" data-id="1">Comment Example - 1</span>
</div>
</div>
<hr>
<div class="d-flex py-2 comments" data-id="2">
<div class="flex-shrink-0">
<img src="https://via.placeholder.com/100" alt="..." />
</div>
<div class="ms-3">
<div class="fw-bold">Name-2
<button type="button" class="update-comment" data-id="2">Edit</button>
</div>
<span class="comment-text" data-text="Comment Example - 2" data-id="2">Comment Example - 2</span>
</div>
</div>
<hr>

Like Count button + Card layout not working properly

enter image description here
I am supposed to have three cards on large screens, 2 in tablets, 1 in mobile and all without hard coded html. Only through javascript. However, when I try to add three cards in the same row, it takes the same movie for the entire row and then the next one for the second row and so on..
Also the button only works for the first card...
There must be smth wrong in my loop..
This is my code so far:
var parsedMovies = JSON.parse(movies);
for (let i = 0; i < parsedMovies.length; i++) {
document.getElementById("cards").innerHTML += `
<div class="card-group">
<div class="card mb-3 bg-dark text-light" style="max-width: 540px;">
<div class="row g-0 ">
<div class="col-md-4 ">
<img src="${parsedMovies[i].image}" class="img-fluid rounded-start" alt="...">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">${parsedMovies[i].title}</h5>
<p class="card-text">${parsedMovies[i].plot}</p>
<p class="card-text"><small class="text-muted"> Year: ${parsedMovies[i].year} <br> Director: ${parsedMovies[i].director} <br> Actors: ${parsedMovies[i].actors}</small>
<div class="voting">
<button id="likebtn">
<i>👍</i>
</button>
<input type="number" id="input1" value="${parsedMovies[i].likes}">
<button id="dislikebtn">
<i>👎</i>
</button>
<input type="number" id="input2" value="${parsedMovies[i].dislikes}">
</div>
</p>
</div>
</div>
</div>
</div>
<div class="card mb-3 bg-dark text-light" style="max-width: 540px;">
<div class="row g-0 ">
<div class="col-md-4 ">
<img src="${parsedMovies[i].image}" class="img-fluid rounded-start" alt="...">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">${parsedMovies[i].title}</h5>
<p class="card-text">${parsedMovies[i].plot}</p>
<p class="card-text"><small class="text-muted"> Year: ${parsedMovies[i].year} <br> Director: ${parsedMovies[i].director} <br> Actors: ${parsedMovies[i].actors}</small>
<div class="voting">
<button id="likebtn">
<i>👍</i>
</button>
<input type="number" id="input1" value="${parsedMovies[i].likes}">
<button id="dislikebtn">
<i>👎</i>
</button>
<input type="number" id="input2" value="${parsedMovies[i].dislikes}">
</div>
</p>
</div>
</div>
</div>
</div>
<div class="card mb-3 bg-dark text-light" style="max-width: 540px;">
<div class="row g-0 ">
<div class="col-md-4 ">
<img src="${parsedMovies[i].image}" class="img-fluid rounded-start" alt="...">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">${parsedMovies[i].title}</h5>
<p class="card-text">${parsedMovies[i].plot}</p>
<p class="card-text"><small class="text-muted"> Year: ${parsedMovies[i].year} <br> Director: ${parsedMovies[i].director} <br> Actors: ${parsedMovies[i].actors}</small>
<div class="voting">
<button id="likebtn">
<i>👍</i>
</button>
<input type="number" id="input1" value="${parsedMovies[i].likes}">
<button id="dislikebtn">
<i>👎</i>
</button>
<input type="number" id="input2" value="${parsedMovies[i].dislikes}">
</div>
</p>
</div>
</div>
</div>
</div>
</div>
`;
let likebtn = document.querySelector("#likebtn");
let dislikebtn = document.querySelector("#dislikebtn");
let input1 = document.querySelector("#input1");
let input2 = document.querySelector("#input2");
likebtn.addEventListener("click", () => {
input1.value = parseInt(input1.value) + 1;
});
dislikebtn.addEventListener("click", () => {
input2.value = parseInt(input2.value) + 1;
});
Your loop is creating multiple time the same ids... An id must be unique.
So, remove all id in the HTML "template" and use a class (I used like-action below) on both the like and dislike buttons.
Then, set ONE event handler for those button, since the action is the same (increment by one). See below:
let likebtns = document.querySelectorAll(".like-action");
likebtns.forEach((button)=>{
button.addEventListener("click", (element) => {
input = element.nextElementSibling
input.value = parseInt(input.value) + 1;
});
});
Have a look at nextElementSibling.

How do I select data from element with onclick listener?

I'm currently working on a web application that has to function as some sort of webshop later on. I'm now working on an addToCart function, that has to pick certain data from the clicked element (the name and the price of the product, and add 1 to pcs and save everything to a session), and paste these 2 values into a template I've made and place this in the shopCart. I'm now trying to print out the 2 values I've just mentioned, but I'm stuck now.
This is the current javascript code I've made for loading in all the products, and my attempt on showing some of the values of the clicked items:
$(function(){
$.getJSON("assets/products/sample_products.json", function(response) {
$.each(response.data, function (i, el) {
let card = $($('#productCard-template').html());
card.find('#cardName').html( el.name);
card.find('#cardPrice').html( '€' + el.price );
card.find('.productItem').attr('data-price', el.price)
.attr('data-article-number', el.article_number)
.attr('data-id', el.id)
.attr('data-name', el.name)
.attr('data-stock', el.stock)
.attr('data-categories', el.categories);
$('#touchViewProducts').append(card);
});
});
});
//onclick function adds data of product to the designated template
function addToCart(){
var value = document.getElementById("productCard").value;
var getDataVal = document.getElementById('productCard-template').getAttribute('data-name', 'data-price');
var total = 0;
console.log(this.data-name)
}
This is the html code of the templates:
<div class="row touchViewSection">
<!-- shopping sector -->
<!-- touchView -->
<!-- categories menu -->
<div class="col-3 categoriesSection">
<div class="categories">
<p style="background-color: white; margin-bottom: 0px" > Categories </p>
<a class="nav-link" id="all" href="#">All</a>
<a class="nav-link" id="knalvuurwerk" href="#">Knalvuurwerk</a>
<a class="nav-link" id="rotjes" href="#">Rotjes</a>
<a class="nav-link" id="siervuurwerk" href="#">Siervuurwerk</a>
</div>
</div>
<!-- categories menu -->
<!-- <p style="background-color: white; margin-bottom: 0px" > Products </p>-->
<div class="col-9 productItems" >
<br>
<div class="row" id="touchViewProducts">
</div>
</div>
</div>
<!--/touchView -->
<!--Keyboard View -->
<div class="row keyboardViewSection">
<div class="col-12 keyboardViewRow">
<table id="data-table" class="table table-bordered" style="width: 100%;">
<thead id="tableHead">
<tr>
<th> # </th>
<th> Product name </th>
<th> Free Stock </th>
<th> Price </th>
<th> Action </th>
</tr>
</thead>
</table>
</div>
</div>
<!--/Keyboard View -->
<div class="footer">
<div class="container">
<p class="text-muted"> Developed by Vesta Group</p>
</div>
</div>
</div>
<!--/shopping sector-->
<div class="col-4 cartSection">
<!--cart-->
<div class="row">
<div class="col-5">Product</div>
<div class="col-1">Pcs.</div>
<div class="col-2">Price</div>
<div class="col-3">Total</div>
</div>
<hr style="background-color: white;">
<div id="output" class="row"></div>
<div class="row shopcardProducts" id="shopcartProducts">
</div>
<div class="row cartCheck">
<div class="col-5">Number of products</div>
<div class="col-1">1</div>
<div class="col-2">Subtotal</div>
<div class="col-3 total">€ 0,00</div>
<div class="col-5"></div>
<div class="col-1"></div>
<div class="col-2">Total </div>
<div class="col-3">€ 0,00</div>
</div>
<div class="row cartCheck">
<div class="col-12 checkoutBtn"> Checkout </div>
<div class="col-6 addDiscountBtn"> Add discount </div>
<div class="col-6 cancelBtn"> Cancel </div>
</div>
<!--buttons-->
<!--/cart-->
</div>
</div>
</div>
<script type="text/template" id="productCard-template">
<div class="col-3 productCard" id="productCard" onclick="addToCart()">
<a href="#" class="productItem">
<div class="card">
<img src="assets/images/Firecracker.jpg" alt="Avatar" style="width: 100%; height: 8vh;">
<div class="container">
<div class="row" style="height: 6vh; max-width: 20ch;">
<p id="cardName"> </p>
</div>
<div class="row" style="height: 50%">
<b><p id="cardPrice"></p></b>
</div>
</div>
</div>
</a>
</div>
</script>
<script type="text/template" id="shopcartRow-template">
<div class="row">
<div class="col-5" id="valueName"> </div>
<div class="col-1" id="valueQty"> </div>
<div class="col-2" id="valuePrice"> </div>
<div class="col-3" id="valueTotal"> </div>
</div>
</script>
Here's an image of what the web app looks like, I hope that could make it more clear.
Because addToCart() is a callback, you can use this to access its context (the caller element):
function addToCart(){
var value = $(this).val(); // what val you want to refer? there are no input in the template
var getDataVal = $(this).find('.productItem').getAttribute('data-name', 'data-price');
var total = 0;
console.log(this.data-name)
}

How to retain the border of selected bootstrap cards even on page refresh?

I am having 6 bootstrap cards now I wrote code for storing the every card details in the local storage and also on click the card will get a border now I want is on page refresh I should retain the border of the card
My html code is:
<div class="row">
<div class="col-4" onclick="getGoal(1)">
<div class="card4 mt-3" id="room_1" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_1"><b>I am redecorating</b></p>
</div>
</center>
</div>
</div>
<div class="col-4" onclick="getGoal(2)">
<div class="card4 mt-3" id="room_2" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_2"><b>I am Moving</b></p>
</div>
</center>
</div>
</div>
<div class="col-4" onclick="getGoal(3)">
<div class="card4 mt-3" id="room_3" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_3"><b>I need help with a layout</b></p>
</div>
</center>
</div>
</div>
<div class="col-4" onclick="getGoal(4)">
<div class="card4 mt-3" id="room_4" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_4"><b>I am looking for a species</b></p>
</div>
</center>
</div>
</div>
<div class="col-4" onclick="getGoal(5)">
<div class="card4 mt-3" id="room_5" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_5"><b>I am moving with someone</b></p>
</div>
</center>
</div>
</div>
<div class="col-4" onclick="getGoal(6)">
<div class="card4 mt-3" id="room_6" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_6"><b>Other</b></p>
</div>
</center>
</div>
</div>
</div>
<!--Loop ends-->
<a class="link mt-3"><u>Dont see your room?</u></a>
<div class="row mb-3">
<div class="col-4 mr-5">
« Home
</div>
<div class="col-4 ml-5">
Next »
</div>
</div>
My JS code:
$(document).ready(function(){
// goals
$("#room_1").click(function(){
$("#room_1").toggleClass("blue");
});
$("#room_2").click(function(){
$("#room_2").toggleClass("blue");
});
$("#room_3").click(function(){
$("#room_3").toggleClass("blue");
});
$("#room_4").click(function(){
$("#room_4").toggleClass("blue");
});
$("#room_5").click(function(){
$("#room_5").toggleClass("blue");
});
$("#room_6").click(function(){
$("#room_6").toggleClass("blue");
});
$("#room_7").click(function(){
$("#room_7").toggleClass("blue");
});
$("#room_8").click(function(){
$("#room_8").toggleClass("blue");
});
$("#room_9").click(function(){
$("#room_9").toggleClass("blue");
});
});
var goal = [];
var goalIds = [];
function getGoal(id) {
if (goal.length > 0) {
var data = {
id: id,
content: $("#cont_" + id).text()
}
var x = JSON.stringify(data)
var index = goal.indexOf(x)
if (index == -1) {
goal.push(x);
} else {
goal.splice(index, 1);
}
} else {
var data = {
id: id,
content: $("#cont_" + id).text()
}
var x = JSON.stringify(data);
goal.push(x);
}
localStorage.setItem("goal", JSON.stringify(goal));
goalIds = goal.map(element => JSON.parse(element).id);
console.log(goalIds);
issample();
}
function issample() {
$("#goal").val(goalIds);
console.log(goalIds);
}
function initGoals() {
var storedNames = JSON.parse(localStorage.getItem("goal") || '[]');
goalIds = storedNames.map(element => JSON.parse(element).id);
}
My codepen link is: https://codepen.io/lakshmi123__/pen/xxbzwNP
function initGoals() {
goal = JSON.parse(localStorage.getItem("goal") || '[]');
goalIds = goal.map(element => JSON.parse(element).id);
goalIds.forEach(function(i){$("#room_"+i).addClass('blue');});
}
initGoals();
but event then, you are filling your goalIds variable right with that function,but you are forgetting to fill the goal variable too ;)

Template tag in HTML: querySelector just return null value

I am making a website for education purpose as well, but I got some error that I cant figure out by myself.
I wrote a template like:
<div class="row" style="height: 75%;" align="center" id="room-list">
<template id="room-template" class="slide">
<div class="col-md-4" id="left-item">
<div class="panel panel-default panel-primary">
<div class="panel-heading">
<span id="room-type"></span>
</div>
<div class="panel-body">
<div id="thumbnail" class="thumbnail" style="width: 300px; height: 300px;"></div>
<div id="utility">
Utilities:
</div>
<div id="price">
Price:
<span id="sale" class="sale"><i class="fa fa-usd" aria-hidden="true"></i></span>
<span id="original" class="original"><i class="fa fa-usd" aria-hidden="true"></i></span>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-default btn-primary" style="width: 100%;">Book now!</button>
</div>
</div>
</div>
<div class="col-md-4" id="center-item">
<div class="panel panel-default panel-primary">
<div class="panel-heading">
<span id="room-type"></span>
</div>
<div class="panel-body">
<div id="thumbnail" class="thumbnail" style="width: 300px; height: 300px;"></div>
<div id="utility">
Utilities:
</div>
<div id="price">
Price:
<span id="sale" class="sale"><i class="fa fa-usd" aria-hidden="true"></i></span>
<span id="original" class="original"><i class="fa fa-usd" aria-hidden="true"></i></span>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-default btn-primary" style="width: 100%;">Book now!</button>
</div>
</div>
</div>
<div class="col-md-4" id="right-item">
<div class="panel panel-default panel-primary">
<div class="panel-heading">
<span id="room-type"></span>
</div>
<div class="panel-body">
<div>
<img id="thumbnail" class="thumbnail" style="width: 300px; height: 300px;">
</div>
<div id="utility">
Utilities:
</div>
<div id="price">
Price:
<span id="sale" class="sale"><i class="fa fa-usd" aria-hidden="true"></i></span>
<span id="original" class="original"><i class="fa fa-usd" aria-hidden="true"></i></span>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-default btn-primary" style="width: 100%;">Book now!</button>
</div>
</div>
</div>
</template>
</div>
And I use jquery to add that template to a append a lot of divs by using template.
var roomList = document.querySelector('template# room-list').content;
for (var i = 0; i < roomEntities.length; i++) {
var room = roomEntities[i];
var price = priceEntities[i];
var type = room.type;
var thumbnail = room.thumbnail;
var sale = price.sale;
var original = price.original;
for (var i = 0; i < 3; i++) {
var slt = "#center-item";
if (i == 0) {
slt = "#left-item";
}
else
slt = "#right-item";
var tpl = document.getElementById('room-template');
tpl.querySelector(slt + '.panel-default .panel-heading #room-type').innerText = type;
tpl.querySelector(slt + '.panel-body #thumbnail').attr('src') = thumbnail;
tpl.querySelector(slt + '.panel-body #sale').innerText = sale;
tpl.querySelector(slt +'.panel-body #original').innerText = original;
roomList.appendChild(tpl.content.cloneNode(true));
}
}
But it always returns error at tpl.querySelector(slt + '.panel-default .panel-heading #room-type').innerText = type; it said Cannot set property innerText of null, it mean cannot find the element in template.
Any advice or recommended. Please help. Many thanks
Change all Selectors in your Code
tpl.querySelector(slt + '.panel-default .panel-heading #room-type').innerText
tpl.querySelector(slt + ' .panel-default .panel-heading #room-type').innerText

Categories