How do I make JS code not affect other DIV? - javascript

Hi I am try to make a list of item, I have "add" and "minus" button for each item. The problem is that the JS code I had control two items together. ex. if I click "add" for item1, then the item2 gets added as well.
Looks like that my JS functions works for all button elements. So when I click a "button" element, all buttons get triggered.
How can I do add them individually?
PS: I guess I need to do something like a specific ID for JS to trigger. My thought is add a unique ITEM ID for each one and trigger the button under that specific ID so other buttons under other ITEM ID don't get triggered.
Here is my HTML code:
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">
¥50
<div class="food-edit">
<button class="btn btn-info" value="50.55" id="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info" value="50.55" id="add">+</button>
</div>
</div>
</div>
</div>
</div>
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">
¥50
<div class="food-edit">
<button class="btn btn-info" value="50.55" id="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info" value="50.55" id="add">+</button>
</div>
</div>
</div>
</div>
</div>
Here is my JS:
var theTotal = 0;
var theSales = 0;
var minusButton = document.getElementById('minus');
if (theSales == 0) {
$(minusButton).hide();
}
$('button').click(function () {
var ID = this.id;
if (ID == "add") {
$(minusButton).show();
theTotal = Number(theTotal) + Number($(this).val());
theSales++;
var num = theTotal.toFixed(2);
$('.total').text("¥" + num);
$('.total-num-of-sales').text(theSales + "份");
$('.num-sales').text(theSales);
};
if (ID == "minus") {
theTotal = Number(theTotal) - Number($(this).val());
theSales--;
var num = theTotal.toFixed(2);
if ( theSales == 0 ) {
$('.total').text("");
$('.total-num-of-sales').text("");
$('.num-sales').text("");
$(minusButton).hide();
}
else if ( theSales > 0 ) {
$('.total').text("¥"+num);
$('.total-num-of-sales').text(theSales + "份");
$('.num-sales').text(theSales);
}
};
});

Don't use multiple id on same page
http://jsfiddle.net/bjc1c9tr/4/
Check this will help you
var theTotal = 0;
var theSales = 0;
var minusButton = $('.minus');
if (theSales == 0) {
$(minusButton).hide();
}
$('button').click(function(){
var ID = $(this).attr('data');
if (ID == "add") {
$(this).parent().find('.minus').show();
theTotal = Number($(this).parent().find('.num-sales').text()) + Number($(this).val());
theSales = Number($(this).parent().find('.num-sales').text()) + Number(1);
var num=theTotal.toFixed(2);
$(this).parent().find('.total').text("¥"+num);
$(this).parent().find('.total-num-of-sales').text(theSales+"份");
$(this).parent().find('.num-sales').text(theSales);
};
if (ID == "minus") {
theTotal = Number($(this).parent().find('.num-sales').text()) - Number($(this).val());
theSales= Number($(this).parent().find('.num-sales').text()) - Number(1);
var num=theTotal.toFixed(2);
if ( theSales == 0) {
$('.total').text("");
$(this).parent().find('.total-num-of-sales').text("");
$(this).parent().find('.num-sales').text("");
$(this).parent().find('.minus').hide();
}
else if ( theSales > 0) {
$(this).parent().find('.total').text("¥"+num);
$(this).parent().find('.total-num-of-sales').text(theSales + "份")
$(this).parent().find('.num-sales').text(theSales);
}
};
});
html (added new classes)
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">¥50
<div class="food-edit">
<button class="btn btn-info minus" value="50.55" data="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info add" value="50.55" data="add">+</button>
</div>
</div>
</div>
</div>
</div>
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">¥50
<div class="food-edit">
<button class="btn btn-info minus" value="50.55" data="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info add" value="50.55" data="add">+</button>
</div>
</div>
</div>
</div>
</div>

$('button').click(function(){
var ID = this.id;
if (ID == "add") {
$(minusButton).show();
theTotal = Number(theTotal) + Number($(this).val());
theSales = Number($(this).parent().find('.num-sales').text())+1;
var num=theTotal.toFixed(2);
$('.total').text("¥"+num);
$('.total-num-of-sales').text(theSales+"份");
$(this).parent().find('.num-sales').text(theSales);
};
if (ID == "minus") {
theTotal = Number(theTotal) - Number($(this).val());
theSales = Number($(this).parent().find('.num-sales').text())-1;
var num=theTotal.toFixed(2);
if ( theSales == 0) {
$('.total').text("");
$('.total-num-of-sales').text("");
$(this).parent().find('.num-sales').text("");
//$('.num-sales').text("");
$(minusButton).hide();
}
else if ( theSales > 0) {
$('.total').text("¥"+num);
$('.total-num-of-sales').text(theSales + "份");
$(this).parent().find('.num-sales').text(theSales);
//$('.num-sales').text(theSales);
}
};
$(this).parent().find('.num-sales').text(theSales);
By this way you can get the parent of clicked button and change the value of .num-sales of the selected parent
https://jsfiddle.net/s2u9eb36/ refer this one

You are mixing the elements because of your id and class selectors.
When you select elements through jQuery by class (like $('.num-sales')), jQuery gives you a collection of all elements that match the selector. In your case, that would be both class="num-sales" elements.
Whenever you then call a function (like .html(theSales)), it will apply that function to each element in the collection, that's why your code is affecting more than one element.
You will need to find a way to distinguish one element of the other. There's quite a few options here, but I like doing it by limiting the scope of my selectors. With this I mean I would first find the food-detail div that contains the clicked element, and then find .num-sales etc... only within that element.
Then you can do the following in your button clicks:
$('button').click(function(){
var ID = this.id;
var element = $(this) //make a jQuery object of the clicked button
// finds the first parent element with class food-detail
var container = element.closest('.food-detail');
// find .num-sales within container
var numSales = container.find('.num-sales')
// continue...
});
in short:
when a button is clicked, find the food-detail div the button is in
.find in only that container instead of using selectors on the entire document
Edit: you should really change the id="Add" and id="minus" on your buttons, ids should be unique on the entire document. You can simply add add or minus as a class instead and check for it with element.hasClass('add').

Related

data- attribute not working to grab dynamic id from foreach

I am using JS in a razor page to grab a dynamic ID from a col in a foreach.
In the past, I have used this and it worked fine. However, it seems that it is currently only grabbing the ID from the first col no matter which one I click.
Can someone please tell me if I am still doing this right? Or if I am missing something. Thank you.
View:
<div class="list-group container" id="JobRequestMonitorTable">
<div class="row list-group-item list-group-item-heading container divTableHeading" style="margin-bottom:0px;">
<div class="col-md-4"> Job Code </div>
<div class="col-md-4"> Description </div>
<div class="col-md-2"> Schedule </div>
<div class="col-md-1"> Running </div>
<div class="col-md-1"></div>
</div>
#if (!string.IsNullOrEmpty(ViewBag.ErrorMessage))
{
<div class="row list-group-item-danger">
<div class="col-md-1 text-center">#ViewBag.ErrorMessage</div>
</div>
}
#foreach (var item in Model.JobRequests)
{
<div class="row list-group-item container">
<div class="hidden" data-id="#item.JobRequestId" id="requestId">#item.JobRequestId</div>
<div class="col-md-4">#item.JobCode</div>
<div class="col-md-4">#item.Description</div>
<div class="col-md-2">#item.Schedule</div>
#if (#item.IsRunning == true)
{
<div class="col-md-1" style="margin-left:25px;"><span class="glyphicon glyphicon-ok"></span></div>
<div class="col-md-1"></div>
}
else
{
<div class="col-md-1"></div>
<div class="col-md-1">
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn"></button>
</div>
}
</div>
}
</div>
JS:
$("button").click(function () {
var col = $('#requestId');
var jobRequestId = col.data('Id');
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var arr = results;
//loop through arr created from dictionary to grab key(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
var myKey = key;
}
}
var name = myKey;
var value = results[myKey];
$('#modalName').text(name);
$('#modalMessage').text(value);
}
});
});
Really the only important part to see in the JS is var col = $('#requestId');
var jobRequestId = col.data('Id');
But I suppose I will include the whole script just in case people ask.
Your loop is creating multiple #requestId and #paramModalBtn elements when id attributes have to be unique within the DOM. Change the logic to use common classes instead. Then you can traverse the DOM to find the elements related to the button which was clicked. Try this:
$("button").click(function() {
var $col = $(this).closest('.row').find('.requestId');
var jobRequestId = $col.data('id');
console.log(jobRequestId);
// AJAX request...
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<div class="row list-group-item container">
<div class="hidden requestId" data-id="foo-bar">Job #1</div>
<!-- other content... -->
<div class="col-md-1">
<button class="glyphicon glyphicon-list-alt btn btn-primary" name="paramsBtn"></button>
</div>
</div>
<div class="row list-group-item container">
<div class="hidden requestId" data-id="lorem-ipsum">#Job #2</div>
<!-- other content... -->
<div class="col-md-1">
<button class="glyphicon glyphicon-list-alt btn btn-primary" name="paramsBtn"></button>
</div>
</div>
All of your items inside the loop are getting the same id attribute, it is hard-codded
id="requestId"
the jQuery selector $('#requestId') is getting back the first one, this is by design.
I would add a data-id to each button and select the relevant col with that id.
For example the button will get:
<button data-col-id="#item.JobRequestId" class="glyphicon glyphicon-list-alt btn btn-primary"></button>
And then, its easy to grab that info on click:
$("button").click(function () {
var jobRequestId = $(this).data('col-id');
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var arr = results;
//loop through arr created from dictionary to grab key(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
var myKey = key;
}
}
var name = myKey;
var value = results[myKey];
$('#modalName').text(name);
$('#modalMessage').text(value);
}
});
});
I like this solution as you are not depended on your HTML structure and hierarchy thus selectors won't break often.
Once you have a button for each item, you could also store the data into the button value attribute, which leads to a simple implementation in the JS:
$("button").click(function (e) {
var jobRequestId = $(e.target).val();
console.log(jobRequestId);
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var arr = results;
//loop through arr created from dictionary to grab key(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
var myKey = key;
}
}
var name = myKey;
var value = results[myKey];
$('#modalName').text(name);
$('#modalMessage').text(value);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="1">Job 1</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="2">Job 2</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="3">Job 3</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="4">Job 4</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="5">Job 5</button>
Obs.: value must be equal to #item.JobRequestId like so: <button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="#item.JobRequestId">Job 5</button>

consecutive html() calls overwrites the first

Here is my jquery
var defaultControlClassic = "<div id='control-textarea-wrapper' class='control'>" + "\n";
defaultControlClassic += "<textarea id='control-textarea' tabindex='1000' rows='1'></textarea>" + "\n";
defaultControlClassic += "<button type='button' class='btn btn-link btn-icon'><i class='material-icons input-send'></i></button>" + "\n";
defaultControlClassic += "</div>" + "\n";
var msg = jsonResponse.html;
intent = jsonResponse.intent;
//Create a dom node out of the response
var div = document.createElement('div');
div.innerHTML = msg.trim();
var domMsg = div.firstChild;
//If Typing animation is happening time to remove it
$('.sender-action').parent('.response').remove();
//Get the Control from the response
var control = domMsg.getElementsByClassName("control")[0];
//Remove the current control from the domMsg
$(domMsg).find('.control').remove();
//Use default control if none specified
if (control === undefined) control = defaultControlClassic;
//Add the control
$('.step-next .controls').html(control);
$('.fixed-control').html(control);
and this works fine with the above text value of "defaultControlClassic"
but when "control" gets assigned by this...
var control = domMsg.getElementsByClassName("control")[0];
The first call to html() works, and so does the second, but but the first gets overwritten by the second one
$('.step-next .controls').html(defaultControlClassic);
$('.fixed-control').html(defaultControlClassic);
Here is the html
<div class="chat-window" >
<header class="chat-header">
<div class="modern-nav d-flex justify-content-between">
<button type="button" class="btn btn-link btn-previous" style="display: none;"><i class="fal fa-long-arrow-left"></i> Previous</button>
<div class="spinner"> </div>
<button type="button" class="btn btn-link btn-restart" style="display: none;">Restart </button>
</div>
<div class="progress" >
<div class="progress-bar" role="progressbar" style="width: 1%;" aria-valuenow="1" aria-valuemin="0" aria-valuemax="100">1%</div>
</div>
</header>
<div class="chat-body">
<div class="step-container">
<form class="step-form step step-next">
<div class="messages" class="" ></div>
<div class="controls" class="" ></div>
</form>
</div>
<div class="fixed-control"></div>
</div>
Sorry guys - it was a confusiong question.
html() is not working unless its actually html - for some reason if its an object it is overwriting
Here is one solution
//Use default control if none specified
if (control === undefined)
control = defaultControlClassic;
else
control = $('<div>').append($(control).clone()).html();

How to find elements with attr id after click?

Basically, I'm working with three tabs called 'Monday', 'Tuesday' and 'Favorites'. I have a toggle icon which is an empty heart at start => ('.favorite i') within each box. If I'm in Monday and click on the icon the empty heart turns to be filled out and the parent is cloned and added to the '#fav' tab.
When clicking in the heart within the cloned div the whole box gets removed from '#fav' tab but the icon within the original div doesn't get empty and keeps filled out.
So I thought the only way to do this was to grab the id from the original and cloned div which is the same and change the toggle class from there.
Any help is appreciated!
I've created this fiddle to give a better overview of the issue:
https://fiddle.jshell.net/itsfranhere/nbLLc3L0/44/
HTML:
<div class="container">
<div class="tabs_main">
<div class="col-md-5"><a data-target="#mon" class="btn active" data-toggle="tab">Monday</a></div>
<div class="col-md-5"><a data-target="#tue" class="btn active" data-toggle="tab">Tuesday</a></div>
<div class="col-md-2"><a data-target="#fav" class="btn active" data-toggle="tab"><i class="fa fa-heart" aria-hidden="true"></i></a></div>
</div>
<div class="tab-content">
<div class="tab-pane active" id="mon">
<br>
<div class="spaces">
<div class="box-container">
<div class="box not-selected" id="box1">
<i class="fa fa-heart-o" aria-hidden="true"></i>
</div>
<div class="box-container">
<div class="box not-selected" id="box1">
<i class="fa fa-heart-o" aria-hidden="true"></i>
</div>
</div>
</div>
<div class="tab-pane" id="tue">
<br>
<div class="spaces">
</div>
</div>
<div class="tab-pane" id="fav">
<br>
</div>
</div>
</div>
JS:
// Clones
$('div.tab-pane').on('click', '.favorite', function(e) {
e.preventDefault();
var par = $(this).parents('.box');
var id = $(this).parents('.parent');
var idFind = id.attr("id");
var idComplete = ('#' + idFind);
console.log(idComplete);
//TOGGLE FONT AWESOME ON CLICK
if ($(par).hasClass('selected')) {
par.find('.favorite i').toggleClass('fa-heart fa-heart-o');
} else {
par.find('.favorite i').toggleClass('fa-heart-o fa-heart');
};
if ($(par.hasClass('selected')) && ($('i').hasClass('fa-heart-o'))) {
par.closest('.selected').remove();
var getIcon = $(this).find('.favorite i').toggleClass('fa-heart-o fa-heart');
}
// Clone div
var add = $(this).parent().parent().parent();
add.each(function(){
if ($(add.find('.not-selected .favorite i').hasClass('fa-heart'))) {
var boxContent = $(add).clone(true, true);
var showHide = $(boxContent).find(".session").addClass('selected').removeClass('not-selected');
var get = $(boxContent).html();
var temp = localStorage.getItem('sessions');
var tempArray = [];
tempArray.push(get);
var myJSONString = JSON.stringify(tempArray);
var parseString = $.parseJSON(myJSONString);
var finalString = myJSONString.replace(/\r?\\n/g, '').replace(/\\/g, '').replace(/^\[(.+)\]$/,'$1').replace (/(^")|("$)/g, '');
var myJSONString = localStorage.setItem('sessions', finalString);
$("#fav").append(tempArray);
};
});
});
What I've tried..
var id = $(this).parents('.parent');
var idFind = id.attr("id");
var idComplete = ('#' + idFind);
if ($(par.hasClass('selected')) && ($('i').hasClass('fa-heart-o'))) {
par.closest('.selected').remove();
var getIcon = $(idComplete).find('.favorite i').toggleClass('fa-heart-o fa-heart');
}

jquery: read inside each div, span and input

I'm creating a project in ASP.NET MVC and jQuery. When a user click on addSentence button, I want to duplicate a div called copythis with all events and insert it in another div called myform.
in copythis I have two div: in the first there is a span called sentence where I insert the text in the input in the second the user can add more then one field with different text.
When the user clicks the button called save I want to read all copythis in myform and create a structure to send to a webapi.
I have a problem is the javascript because I can read properly each div.
$("#addSentence").on("click", function (event) {
if ($("#inputSentence").val() == "")
alert("Sentence must have a value");
else {
event.preventDefault();
var theContainer = $("#copythis");
if (theContainer != null) {
var clonedSection = $(theContainer).clone(true);
if (clonedSection != null) {
$(clonedSection).find("#sentence")
.text($("#inputSentence").val());
$(clonedSection).appendTo("#myform");
}
}
}
});
$("#save").on("click", function (event) {
$("#myform #copythis").children().each(function (index, element) {
var elm = $(this);
var sentence = elm.find('.row span#sentence').val();
if (sentence != '') {
console.log('Sentence: ' + sentence);
$("input").children().each(function (m, l) {
var txt = $(this).val();
if (txt != '') {
console.log('Example: ' + txt);
}
});
}
});
});
function makeRepeater(sectionsSelector, addClass, removeClass, AYSMsg) {
$(sectionsSelector + " " + addClass + "," + sectionsSelector +
" " + removeClass).on("click", function (event) {
// Avoiding the link to do the default behavior.
event.preventDefault();
// Get the container to be removed/cloned
var theContainer = $(this).parents(sectionsSelector);
if ($(this).is(addClass)) {
// Cloning the container with events
var clonedSection = $(theContainer).clone(true);
// And appending it just after the current container
$(clonedSection).insertAfter(theContainer);
} else {
// If the user confirm the "Are You Sure" message
// we can remove the current container
if (confirm(AYSMsg)) {
// Making fade out, hide and remove element a sequence
// to provide a nice UX when removing element.
$(theContainer).fadeOut('normal',
function () {
$(this).hide('fast',
function () { $(this).remove(); }
);
}
);
}
}
});
}
makeRepeater(
'.my-repeated-section-form', /* The container selector */
'.addform', /* The add action selector */
'.removeform', /* The remove action selector */
'Are you sure you want to remove this section?' /* The AYS message. */
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="row">
<div class="row">
<div class="col-lg-10">
<div class="input-group">
<input id="inputSentence" type="text"
class="form-control" placeholder="Sentence...">
<span class="input-group-btn">
<button class="btn btn-secondary"
type="button" id="addSentence">Add</button>
</span>
</div>
</div>
</div>
<div class="col-lg-12">
<div style="display: inline;">
<div class="group-of-repeated-sections" style="display: none;">
<div class="my-repeated-section">
<div id="copythis">
<div class="row">
<div class="col-lg-10">
<span id="sentence"></span>
</div>
<div class="col-lg-2">
<span>
+
-
</span>
</div>
</div>
<div class="my-repeated-section-form">
<div class="row">
<div class="col-lg-12">
<input type="text" />
<span>
+
-
</span>
</div>
</div>
</div>
<div style="height:25px;"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="myform"></div>
<button id="save">Save</button>

how to create generic html with javascript

I have the following html:
<div id="prog" class="downloads clearfix">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label id="pr1"></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a id="pdfdocument" class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
I want build HTML which is inside the <div id="prog"> with Javascript:
<div id="prog" class="downloads clearfix"></div>
I'm trying to use this Javascript, but without success:
var tmpDocument, tmpAnchorTagPdf, tmpAnchorTagXls, parentContainer, i;
parentContainer = document.getElementById('prog');
for (i = 0; i < documents.length; i++) {
tmpDocument = documents[i];
tmpAnchorTagPdf = document.createElement('a id="pdfdocument" ');
tmpAnchorTagPdf.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagPdf.innerHTML = 'start Download';
tmpAnchorTagXls = document.createElement('a');
tmpAnchorTagXls.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagXls.innerHTML = 'start Download';
parentContainer.appendChild(tmpAnchorTagPdf);
parentContainer.appendChild(tmpAnchorTagXls);
}
If this is a section of code that you will be using more than once, you could take the following approach.
Here is the original div without the code you want to create:
<div id="prog" class="downloads clearfix">
</div>
Create a template in a hidden div like:
<div id="itemtemplate" style="display: none;">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
Then duplicate it with jquery (OP originally had a jquery tag; see below for JS), update some HTML in the duplicated div, then add it to the document
function addItem() {
var item = $("#itemtemplate div.item").clone();
//then you can search inside the item
//let's set the id of the "a" back to what it was in your example
item.find("div.link a").attr("id", "pdfdocument");
//...the id of the label
item.find("div.title label").attr("id", "pr1");
//then add the objects to the #prog div
$("#prog").append(item);
}
update
Here is the same addItem() function for this example using pure Javascript:
function JSaddItem() {
//get the template
var template = document.getElementById("itemtemplate");
//get the starting item
var tempitem = template.firstChild;
while(tempitem != null && tempitem.nodeName != "DIV") {
tempitem = tempitem.nextSibling;
}
if (tempitem == null) return;
//clone the item
var item = tempitem.cloneNode(true);
//update the id of the link
var a = item.querySelector(".link > a");
a.id = "pdfdocument";
//update the id of the label
var l = item.querySelector(".title > label");
l.id = "pr1";
//get the prog div
var prog = document.getElementById("prog");
//append the new div
prog.appendChild(item);
}
I put together a JSFiddle with both approaches here.

Categories