How to loop div like angular js using pure javascript - javascript

I have use this following technique to replace sting in html.
var str = "Some html values";
var res = str.replace("{company}","Microsoft");
But i want to loop div like angular js by using pure JavaScript like shown below
{foreach value in values} <div class="test">{value}</div> {/foreach}
if anyone knows please let me know

Here is a way in vanilla JS :
var values = ["Microsoft", "Apple", "Amazon"];
var node = document.getElementById( "myDiv" );
var res="";
for (id in values){
res+="<p>"+values[id]+"</p>";
}
node.innerHTML=res;
<div id='myDiv'></div>

I have found the solution
var values = '';
var alphabet = ['a','b','c','d','e'];
var meanings = ['apple','banana','choclate','dominoes pizza','eggs']
var value = document.getElementById("test1").innerHTML;
for (var i=0; i<alphabet.length; i++) {
values += value.replace("{value}",alphabet[i]).replace("{meanings}",meanings[i]);
}
document.getElementById("test2").innerHTML = values;
<div id="test2" class="test">
<div id="test1" class="test">
<div class="test">
{value} for {meanings}
</div>
</div>
</div>

Related

How to find element in string by class using JavaScipt?

For example I have a string with html code.
const string = `
<div>
<h1>Title</h1>
<h2>Subtitle</h2>
<div class="find-me">text</div>
</div>
`;
Expected result with JS script:
<div class="find-me">text</div>
How it's possible to do it without jquery and other libraries/frameworks ?
Try this
const string = `
<div>
<h1>Title</h1>
<h2>Subtitle</h2>
<div class="find-me">text</div>
</div>
`;
let arr = string.split('\n');
for(let i=0; i<arr.length; i++){
if(arr[i].search("find-me") != -1){
console.log(arr[i]);
}
}
you can create a temporary element and attach the string using innerHTML:
let tempElement = document.createElement("div");
tempElement.innerHTML = string;
const myElement = tempElement.querySelector(".find-me");

Confused creating a HTML divs using Javascript

I'm writing a code where in there is a json given and out of the key value pairs of json I need to create HTML divs.
Here is my HTML
<div id="col-md-12">
</div>
<input type="button" onclick="addDivs()" />
and my JS
function addDivs() {
var jsonInput = {
'a': '1',
'b': '2'
}
var colDiv = document.getElementById("col-md-12");
var row = document.createElement("div");
row.className = "row";
Object.keys(jsonInput).forEach(function(k) {
var string = k;
var range = jsonInput[k];
var col4Div = document.createElement("div");
col4Div.className = "col-md-4 icon-plus";
var alcohol = document.createElement("span");
alcohol.className = string;
var strong = document.createElement("strong");
strong.innerHTML = string;
var dropDownArrow = document.createElement("span");
dropDownArrow.className = "down-arrow";
alcohol.innerHTML = strong;
alcohol.innerHTML = dropDownArrow;
alcohol.innerHTML = "<br/>";
alcohol.innerHTML = range;
col4Div.innerHTML = alcohol;
row.innerHTML = col4Div;
});
colDiv.innerHTML=row;
}
when I click the button, it gives me message as [object HTMLDivElement] and in console it shows no error.
I'm really confused on what's going on in the backend. My expected output is
<div class="col-md-12">
<div class="row">
<div class="col-md-4 icon-plus">
<span class="a">
<strong>a</strong>
<span class="down-arrow"></span>
<br /> 1</span>
</div>
<div class="col-md-4 icon-plus">
<span class="b">
<strong>b</strong>
<span class="down-arrow"></span>
<br /> 2</span>
</div>
</div>
</div>
please let me know where am I going wrong and how can I fix it.
Here is a working fiddle. https://jsfiddle.net/p9e7cLg9/1/
Thanks
innerHTML deals in strings (of HTML source code). createElement deals in DOM nodes.
When you convert a DOM node to a string, you get "[object HTMLDivElement]", which isn't useful, so don't do that.
Use the appendChild method to add a DOM node as a child of an existing HTML element.

Append/Pass the array values from javascript to HTML Div?

var array = []; //In this i have 2 items
<div id="content"></div>
In this div id I need to pass the above array elements.
Ho can I do this?
Below is the basic example, how you interact with your DOM with javascript.
var array = [1, 2];
var content = document.getElementById("content");
for(var i=0; i< array.length;i++){
content.innerHTML += i + '--' + array[i] + '<br>';
}
<div id="content">
</div>
Big Note:
You can also use Javascript Templating if you are looking for passing a lot of other data as well to the View
You can use document.getElementById to get the id of the <div> and then insert the array as a string which will convert to the comma separated value:
var array = ['apple','ball']; //In this i have 2 items
document.getElementById('content').innerHTML = array.toString();
<div id="content"></div>
You Looking for Something like this ?
<div class="dummy" style="height: 100px;width: 100px;border: 1px solid black;"></div>
jQuery(document).ready(function(){
var arr = ['1','2'];
jQuery.each( arr, function( i, val ) {
jQuery('.dummy').append(val);
jQuery('.dummy').append("<br>");
});
});
jsfiddle : https://jsfiddle.net/vis143/c1kz0b8o/

How to create a clickable list of divs with sub items using JavaScript

I want to create a list of clickable divs from arrays using Javascript, where the list structure has to be something like this:-
<div id="outerContainer">
<div id="listContainer">
<div id="listElement">
<div id="itemId"> </div>
<div id="itemTitle"> </div>
<div id="itemStatus"> </div>
</div>
<div id="listElement">
<div id="itemId"> </div>
<div id="itemTitle"> </div>
<div id="itemStatus"> </div>
</div>
</div>
</div>
I want to extract the values of itemId, itemTitle and itemStatus from three arrays itemIdData[ ], itemTitleData[ ] and itemStatusData[ ] respectively, to create the whole list.
Also, when I click on any of the listElements, I want an alert showing the itemId. Can anyone help me with this problem.
If you're using jQuery, then try something like this:
$("#listContainer").on("click", "div", function () {
console.log("jQuery Event Delegation");
alert($(this).find(">:first-child").attr("id"));
});
It's possible to write the same thing without jQuery, but will take further lines of code - I'm conveying the idea of delegation here (there are extensive existing docs and examples on the JQuery site, and here on this site).
NB: the code you're submitted in the question can't(shouldn't) have multiple DOM elements with same IDs (that's what classes are for - for semantically similar elements). Also, trying to emulate a list using divs instead of li elements is perhaps not best practice.
After a bit of experimentation, understood what I was doing wrong and how to get it done.
Here's the code:-
var listContainer = document.createElement("div");
document.getElementById("outerContainer").appendChild(listContainer);
for (var i = 0; i < json.length; i++) {
//create the element container and attach it to listContainer.
var listElement = document.createElement("div");
listElement.id = i;
listElement.className = "listItemContainer";
listElement.addEventListener("click", function(e){
var itemId = e.target.children[1].innerHTML;
alert(itemId);
});
listContainer.appendChild(listElement);
//create and attach the subchilds for listElement.
var itemTitle = document.createElement("span");
itemTitle.innerHTML = postTitleData[i];
itemTitle.id = 'title'+i;
itemTitle.className = "itemTitle";
listElement.appendChild(itemTitle);
var itemId = document.createElement("div");
itemId.innerHTML = postIdData[i];
itemId.id = 'id'+i;
itemId.className = "itemId";
listElement.appendChild(itemId);
var itemStatus = document.createElement("span");
itemStatus.innerHTML = postStatusData[i];
itemStatus.id = 'status'+i;
itemStatus.className = "itemStatus";
listElement.appendChild(itemStatus);
}
Tried something like this which isn't quite working!
var listContainer = document.createElement("div");
document.getElementById("outerContainer").appendChild(listContainer);
var listElement = document.createElement("div");
listContainer.appendChild(listElement);
listElement.className = "listItemContainer";
for (var i = 0; i < json.length; i++) {
var itemId = document.createElement("div");
itemId.innerHTML = idData[i];
listElement.appendChild(itemId);
itemId.className = "itemId";
var itemTitle = document.createElement("div");
itemTitle.innerHTML = titleData[i];
listElement.appendChild(itemTitle);
itemTitle.className = "itemTitle";
var itemStatus = document.createElement("div");
itemStatus.innerHTML = statusData[i];
listElement.appendChild(itemStatus);
itemStatus.className = "itemStatus";
listElement.appendChild(document.createElement("hr"));
var elementId = 'ListElement'+i;
listElement.id = elementId;
listElement.addEventListener("click", function(){
alert(document.getElementById(elementId).innerHTML);
});
}

How to get child element by ID in JavaScript?

I have following html:
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
How can I get textarea element? I can't use document.getElementById("textid") for it
I'm doing it like this now:
var note = document.getElementById("note");
var notetext = note.querySelector('#textid');
but it doesn't work in IE(8)
How else I can do it? jQuery is ok
Thanks
If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.
$('#note').find('#textid');
You can also use jQuery selectors to basically achieve the same thing:
$('#note #textid');
Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.
On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.
Update 2020.03.10
It's a breeze to use native JS for this:
document.querySelector('#note #textid');
If you want to first find #note then #textid you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(
var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;
Here is a pure JavaScript solution (without jQuery)
var _Utils = function ()
{
this.findChildById = function (element, childID, isSearchInnerDescendant) // isSearchInnerDescendant <= true for search in inner childern
{
var retElement = null;
var lstChildren = isSearchInnerDescendant ? Utils.getAllDescendant(element) : element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].id == childID)
{
retElement = lstChildren[i];
break;
}
}
return retElement;
}
this.getAllDescendant = function (element, lstChildrenNodes)
{
lstChildrenNodes = lstChildrenNodes ? lstChildrenNodes : [];
var lstChildren = element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].nodeType == 1) // 1 is 'ELEMENT_NODE'
{
lstChildrenNodes.push(lstChildren[i]);
lstChildrenNodes = Utils.getAllDescendant(lstChildren[i], lstChildrenNodes);
}
}
return lstChildrenNodes;
}
}
var Utils = new _Utils;
Example of use:
var myDiv = document.createElement("div");
myDiv.innerHTML = "<table id='tableToolbar'>" +
"<tr>" +
"<td>" +
"<div id='divIdToSearch'>" +
"</div>" +
"</td>" +
"</tr>" +
"</table>";
var divToSearch = Utils.findChildById(myDiv, "divIdToSearch", true);
(Dwell in atom)
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
<script type="text/javascript">
var note = document.getElementById('textid').value;
alert(note);
</script>
Using jQuery
$('#note textarea');
or just
$('#textid');
$(selectedDOM).find();
function looking for all dom objects inside the selected DOM.
i.e.
<div id="mainDiv">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<div id="innerDiv">
link
<p>Paragraph 3</p>
</div>
</div>
here if you write;
$("#mainDiv").find("p");
you will get tree p elements together. On the other side,
$("#mainDiv").children("p");
Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.

Categories

Resources