Counting variable name, which will get appended - javascript

I have some trouble with my web project.
I'm looking for a solution how I can count my variable upwards in a loop.
So that the name of the variable will go like this: panel1, panel2, panel3...
Thats my code
var panel = []
for(i=1; i<3; i++){
var $div = $('<div class="panel3" id="panel3">Box2 - 20</div>');
$('.panel[i]').append($div);
}
so the "panel[i]" at the bottom should get a higher number for every loop.
I was looking a long time for a solution, but nothing worked.
The idea behind my code is to fill all those empty boxes with a div.
Some HTML
<div class="panel-body">
<!-- Reihe 1 -->
<div class="row">
<div class="col-md-2">
<div class="panel1">
</div>
</div>
<div class="col-md-2">
<div class="panel2">
</div>
</div>
And so on...
Thanks for the help

If your panel name will be panel1, panel2, panel3, so on then you cannot do with this $('.panel[i]'). Instead of that do something like,
for(i=1; i<3; i++){
var div = $('<div class="panel3">Box2 - 20</div>');
var panelClass = '.panel'+i;
$(panelClass).append(div);
}
Hope it helps.

All you need to do is String concatenation with the value of i
var $div = $('<div class="panel3" id="panel'+i+'">Box2 - 20</div>');
And also in the below you doesn't need an array. Just use the parent container identity
$(parentSelector).append($div);
In case if you need all the html in an array
panel[i] = $div;

Related

change label foreach element in html using javascript

I am using both html and velocity and came up with this code. The names and images are stored in an array and this is the code I used to display each of the contents of this array to the page.
#foreach($starter in $starter)
<div class="product">
<div class="color"><img src= "$starter.img" width="100" height="100"></div>
<span class="product-name">$starter.name</span>
<div class="compare-wrap">
<input type="checkbox" id="">
<label id="view">Compare</label>
</div>
</div>
#end
I wanted the label to change from "Compare" to "View Compare" while at the same time storing its id in the array upon checking their correspondng check box. I eventually came up with this code:
var checkedArray = [];
$(":checkbox").change(function(){
if((this).checked){
checkedArray.push(this.id);
document.getElementById('view').innerHTML = "<a href='/compare'>View Compare</a>";
}
else{
checkedArray.splice(checkedArray.indexOf(this.id), 1);
document.getElementById('view').innerHTML = 'Compare';
}
var str = checkedArray.join(', ');
alert(str);
});
but it seems it is only applicable to the first content of the array. Any idea how I can use a foreach code at this point?
document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You should use a class:
var views = document.getElementsByClassName('view');
var i = views.length;
while(i--) {
views[i].innerHTML = "Compare";
}
HTML
<label class="view">Compare</label>
Element ID must be unique.
Hope it helps.

How to make all child elements red

This is the html code:
<div id="sm-responsive-one">
<p> Step one </p>
<div style="">1</div>
<div style="">2</div>
<div style="">3</div>
<div style="">4</div>
</div>
<div id="sm-responsive-two">
<p> Step two </p>
<div style="">5</div>
<div style="">6</div>
<div style="">7</div>
<div style="">8</div>
</div>
Problem: I want to make 1,2,3 and 4 (child element of sm-responsive-one read color using JavaScript and without using any loop. Is it possible?
This is the code I am trying:
<script>
document.getElementById("sm-responsive-one").getElementsByTagName("div").style.color="red";
//document.getElementById("sm-responsive-one").getElementsByTagName("div")[2].style.color="red";
</script>
You need to use a loop, as getElements* return pseudo-arrays.
If you don't want to use the literal loop syntax, you could apply Array.prototype.forEach, but that's still a loop internally.
var children = document.getElementById("sm-responsive-one").getElementsByTagName("div");
Array.prototype.forEach.call(children, function (it) {
it.style.color="red";
});
First add this CSS rule:
.red-children div {color: red}
Then the javascript is:
document.getElementById('sm-responsive-one').className = "red-children"
getElementsByTagName returns HTML elements collection, so you need to iterate over them:
var elements = document.getElementById("sm-responsive-one").getElementsByTagName("div");
for( var i = 0, len = elements.length; i < len; i++ ) {
elements[ i ].style.color = 'red';
}
Try this:
$("#sm-responsive-one > div").css("color","red");
Check this fiddle:
http://jsfiddle.net/v6xxws1z/

document.getElementById like function for a particular div

document.getElementById will search th whole document and return the result but here i want the same function for a particular div as i want to search the specific div for an id and based on that i want to execute
here is my code
if(document.getElementById('myId') ) // but it return the result from whole div
{
// Do something
}
else {
// do something else
}
i want something like
if(document.getElementById('myId') in specific div) \\ how to do this
Let say, you are looking for an element(div) with id "childId" within parent div with id "parentId". The Jquery code would be:
$("#parentId").find("#childId")
As a shortform, you can even do
$("#parentId #childId")
Since the above statement will find children in any depth, if you would want a direct child search, (first level child)
$("#parentId > #childId")
Generally ids are unique within the page (or atleast are recommended to be :) ). In such a case, you can directly do
$("#childId")
and still get the child element.
Whichever applies.
You want to search for a specific id for all div
I assume that you know the id you want to search
You can itenerate the document.getElementsByTagName('div') like this
var myID = 4;
for (var i = 0; i < document.getElementsByTagName('div').length; i++){
var res = document.getElementsByTagName('div')[i+1].id;
if(res == myID){
document.body.innerHTML = res;
break;
}
}
And this would be your HTML look like:
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
See Demo here
Or I further assume that yor HTML code is look something like this:
<div id="myId">
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
</div>
Then you can itenerate the document.getElementById('myId').getElementsByTagName('div') like this:
var myID = 3;
for (var i = 0; i < document.getElementById('myId').getElementsByTagName('div').length; i++){
var res = document.getElementsByTagName('div')[i+1].id;
if(res == myID){
document.body.innerHTML = res;
break;
}
}
And See Another Demo Here
id attributes should be unique, so searching an element with an id within another element it's the same as search for that id directly in the whole DOM.
You can return an element only if it is a child of a particular element by using a querySelector:
document.getElementById('evalBar').querySelector('#button_2');
/* returned value: (html BUTTON)
[object HTMLButtonElement]
*/
You could use the querySelector function. IMPORTANT: check browser compatibility!
https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
Example:
<div id="foo">
<div id="bar">
this is foo-bar
</div>
</div>
<script>
var bar = document.querySelector("#foo #bar")
alert(bar.innerHTML); // result: alert message "this is foo-bar"
</script>

javascript/jquery get the ID of a div

I have two divs like so:
First Div
<div class="carousel">
<div class="item active" id="ZS125-48A">...</div>
<div class="item" id="FFKG-34">...</div>
<div class="item" id="DSSS-56">...</div>
<div class="item" id="ZSFD-48A">...</div>
</div>
Second Div
<section class="contentBikeTabbedMenus">
<div id="ZS125-48ATab" class="active" "="">...</div>
<div id="FFKG-34Tab" class="" "="">...</div>
<div id="DSSS-56Tab" class="" "="">...</div>
<div id="ZSFD-48ATab" class="a" "="">...</div>
</section>
The first div is a simpled down version of a carousel i have on the page with items like so. I am able to get the id of the active item and store this ready for use.
For the second div i am trying to get the id of the same div with the same id appended with the word 'Tab'.
Heres my code:
// get the carousel
var $carousel = $(".carousel");
var $active = $carousel.find(".item.active").attr('id');
var $bikeId = $active;
var $bikeIdTab = $bikeId + "Tab";
//This prints out the correct id of the item with the class active.
var $tab = $(".contentBikeTabbedMenus");
var $tabId = $tab.find($bikeIdTab);
//i am trying to do the same here but i am having no success.
console.log($bikeIdTab);
console.log($tabId);
Logically i thought that i have the correct id of the div i want to find, but it is not returning this.
How can i get the id of the second div that is the same as the first div. so if the first id is ZS125-48A i can find the div with the id ZS125-48ATab.
Thanks
Simply replace
var $tabId = $tab.find($bikeIdTab);
with
var $tabId = $('#'+$bikeIdTab);
Note: I would prefer to avoid the $ as first char of variable name if these are not jQuery Object: it could confuse us.
You need to prepend the ID pre-selector (#). For example:
var $tabId = $tab.find('#'+$bikeIdTab);
Also, since IDs should be unique, there's no need to use find(). Specifying the selector on its own should be sufficient:
var $tabId = $('#'+$bikeIdTab);
You just missed the # to find the ID in line 8:
// get the carousel
var $carousel = $(".carousel");
var $active = $carousel.find(".item.active").attr('id');
var $bikeId = $active;
var $bikeIdTab = $bikeId + "Tab";
//This prints out the correct id of the item with the class active.
var $tab = $(".contentBikeTabbedMenus");
var $tabId = $tab.find('#' + $bikeIdTab);
//i am trying to do the same here but i am having no success.
console.log($bikeIdTab);
console.log($tabId);

how to remove the lastchild element of dynamically generated DIV and return the html as string

How to remove the lastchild of the dynamically generated div and regenerate the html as string.
Sample HTML DIV
strHtmlString = "<div contenteditable='true' id='undefined'>Test1</div>
<div contenteditable='true' id='sentenceFreeTextField67' type='sentenceFreeTextField'>One</div>
<div id='multiselectAnchors' type='multi'>
<div id='options32' >Two</div>
<div contenteditable='true' id='sentenceFreeTextField68' type='sentenceFreeTextField'>One</div>
</div>
<div id='blank4' contenteditable='true' type='blankField'> </div>
<div id='Div1' type='multi'>
<div id='options33' >Three</div>
<div contenteditable='true' id='sentenceFreeTextField69' type='sentenceFreeTextField'>One</div>
</div>"
here is the code sample
if (($('<DIV/>').html(strSentence)[0].lastChild.lastChild.type === 'sentenceFreeTextField') && (!$.trim($('<DIV/>').html(strSentence)[0].lastChild.lastChild.innerText))) {
strHtmlString = $('<DIV/>').html(strSentence)[0].lastChild.lastChild.remove().html; (this remove().html doesn't work)
}
the need is to delete the lastchild of the div at runtime and convert back to string as it was earlier. I can do string manipulation however, might not the be the right way, please suggest
var el = $(strHtmlString);
// dont know what you meant by last child, so taking the id
el.children().find("#sentenceFreeTextField69").remove();
var str = el.wrap("<div/>").parent().html()
Generate a DIV dynamically:
$('body').append('<div>');
Access the DIV immediately after generation:
var $divElement = $('body').append('<div>').find('div');
Get the last child:
var $lastChildElement = $divElement.last();
Get the HTML of the last child (more specifically, the innerHTML):
var $lastChildHTML = $lastChildElement.html();
Do it all together then you turn around:
var $lastChildHTML = $('body').append('<div>').find('div').last().html();
That's what it's all about.
var last = $(element).children(':last-child');
var html = $(last).html();
$(last).remove();
var newHtml = $(element).html();
//incase you want the html with it's parent as well do this
var newHtml = $(element).parent().html();

Categories

Resources