Confused creating a HTML divs using Javascript - 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.

Related

Cant get CSS property from child?

I have this HTML code here :
<div id="ctr" class="faden-slider-container">
<div class="conteneur-image" ></div>
<div class="conteneur-image" ></div>
<div class="conteneur-image" ></div>
</div>
And I am trying to get the CSS property of the second div which class' name is conteneur-image but I get nothing :
app.controller("slideCtrl",function ($scope) {
alert("hello")
var tab = new Array();
var elements = new Array();
for(var i = 0; i<3 ; i++){
elements[i] = document.getElementById("ctr").children[i]
}
var style = window.getComputedStyle(elements[1])
var message = style.getPropertyCSSValue("background").cssText()
alert("CSS Value is : "+message)
})
Couple of issues there.
getPropertyCSSValue is obsolete and may not work in browsers anymore
id is a selector, not a valid css property
Use getPropertyValue instead,
var message = style.getPropertyCSSValue("background");
Demo
var style = window.getComputedStyle(document.getElementById("ctr").children[1])
var message = style.getPropertyValue("background");
console.log("CSS Value is : " + message)
<div id="ctr" class="faden-slider-container">
<div class="conteneur-image"></div>
<div class="conteneur-image"></div>
<div class="conteneur-image"></div>
</div>
Using jquery,you can get your 2nd HTML element this way:
var element = $("#ctr").children().eq(1);
Then if you want to make some transformation, like applying style:
element.css("background-color", "blue")
Here is a snippet:
var element = $("#ctr").children().eq(1);
element.css("background-color", "blue")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ctr" class="faden-slider-container">
<div class="conteneur-image" >one</div>
<div class="conteneur-image" >second</div>
<div class="conteneur-image" >third</div>
</div>

How to loop div like angular js using pure 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>

How can I get the matched element's parent div attribute by regular express using Javascript

Have a html string see below.
<div sentence="11">
<p>
how are you Tom, how are you Tom
</p>
</div>
<div sentence="12">
<p>
how are you Tom
</p>
</div>
When user select the name 'Tom', I will replace the string 'Tom' using a name tag with some html style. The result what I want see below.
<div sentence="11">
<p>
how are you <span class="ano-subject" data-oristr="Tom" data-offset="1" data-sentence="11"><NAME></span>, how are you <span class="ano-subject" data-oristr="Tom" data-offset="2" data-sentence="11"><NAME></span>
</p>
</div>
<div sentence="12">
<p>
how are you <span class="ano-subject" data-oristr="Tom" data-offset="1" data-sentence="12"><NAME></span>
</p>
</div>
I will using the code below to do the replace.
var content = HTML CODE ABOVE;
var selectText = 'Tom';
var regex = new RegExp('(?=\\s|^|\\b)(?:' + selectText + ')(?=\\s|$|\\b)', "g");
var pre_sentence = 0;
var offset = 0;
content = content.replace(regex, function(match, position) {
var curr_sentence = ???; // how can I get this element's parent div attribute 'sentence' ?
if(pre_sentence != cur_sentence){
// this is new sentence.
offset = 1;
pre_sentence = curr_sentence;
} else {
offset++;
}
var replace = '<span class="ano-subject" data-oristr="Tom" data-offset="'+offset+'" data-sentence="'+curr_sentence+'"><NAME></span>';
return replace;
});

how to get specific values from string?

I am getting a variable which value always follows this format:
"<div>
</div>
<div>
<span style="font-family:tahoma,geneva,sans-serif;"><span>VALUE 1</span></span></div>
<div>
<strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div>
<div>
<span style="font-family:tahoma,geneva,sans-serif;"> </span>VALUE 3</div>
"
How can I get VALUE 1, VALUE 2 and VALUE 3 using JavaScript (not jQuery or other libs)?
NB:
in Console, I get those values (I call them b)
typeof(b) returns string
The most simplest way using jQuery.
var a = '<div>\
</div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;"><span>VALUE 1</span></span></div>\
<div>\
<strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;">au </span>VALUE 3</div>'
var HTML = $.parseHTML(a)
var val1 = $(HTML[1]).find('span span').text()
var val2 = $(HTML[2]).find('span').text()
$(HTML[3]).find('span').remove()
var val3 = $(HTML[3]).text()
console.log(val1, val2, val3)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Use Array#map and then Array#filter
innerHTML the string to a temp element and use DOM-api to manipulate data.
Use 'span[style]' selector to get only those span elements having style attribute.
var str = '<div>\
</div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;"><span>VALUE 1</span></span>\
</div>\
<div>\
<strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;">VALUE 3</span></div>';
var div = document.createElement('div');
div.innerHTML = str;
var spanElems = div.querySelectorAll('span[style]');
var spans = [].map.call(spanElems, function(el) {
return el.textContent.trim();
}).filter(Boolean);
console.log(spans);
You can save the string as a variable, and then use htmlString.match(/VALUE \d+/gmi)
Update:
If the input is a valid HTML string you could parse with this trick (not jQuery or other libs):
var your_string = `<div> </div><div><span style="font family:tahoma,geneva,sans-serif;"><span>VALUE 1</span>fgfgfg</span></div><div><strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div><div><span style="font-family:tahoma,geneva,sans-serif;"> </span>VALUE 3</div>`
var obj_evaluator = document.createElement("div");
obj_evaluator.innerHTML = your_string;
// get the list of div
var list_div = obj_evaluator.getElementsByTagName('div');
var value1 = (list_div[1].firstChild.firstChild.textContent); //value 1
var value2 = (list_div[2].firstChild.firstChild.textContent); //value 2
var value3 = (list_div[3].lastChild.textContent); //value 3
// create an array
var result = [value1,value2,value3]
// print result
console.log(result);
Old answer (wrong because of the VALUE 3,but if all the VALUE are inside the 'span' then this is the right answer! ):
var obj_evaluator = document.createElement("div");
obj_evaluator.innerHTML = your_string;
// debug row
console.log(obj_evaluator);
var list_span = obj_evaluator.getElementsByTagName('span');
for (var i = 0; i < list_span.length; i++) {
console.log(list_span[i].innerHTML);
// here you can print other info of the node
}

Dynamically adding div using javascript

I have below html:
<div id="DetailsPanel" class="panel">
<div class="body stack-calc">
<div class="form stack-elem">
<div class="field">
</div>
//I want append my new Dynamically created DIV here
<div id="BusinessUnitsContainer" class="field">
</div>
</div>
</div>
</div>
Javascript:
var mainDiv = document.createElement('div');
mainDiv.className = 'field';
var innerDiv = document.createElement('div');
innerDiv.className = 'SelectAllCheckBox';
var newlabel = document.createElement("Label");
newlabel.innerHTML = "Select All";
var selectCheckbox = document.createElement('input');
selectCheckbox.type = "checkbox";
selectCheckbox.name = "selectCheckbox";
selectCheckbox.id = "selectCheckboxID";
selectCheckbox.checked = true;
innerDiv.appendChild(selectCheckbox);
innerDiv.appendChild(newlabel);
mainDiv.appendChild(innerDiv);
var BusinessUnitsContainerID = document.getElementById('BusinessUnitsContainer');
var DetailsPanelID = document.getElementById('DetailsPanel');
DetailsPanelID.insertBefore(mainDiv,BusinessUnitsContainerID);
I am getting "Error: NotFoundError: Node was not found"
Any idea
You are using a mix of jQuery and native node insertBefore.
Using jQuery
$("#BusinessUnitsContainer").before(mainDiv);
javascript
In your code the problem is BusinessUnitsContainer is not a direct child of DetailsPanel element.
var BusinessUnitsContainerID = document.getElementById('BusinessUnitsContainer');
BusinessUnitsContainerID.parentNode.insertBefore(mainDiv,BusinessUnitsContainerID);
Demo: Fiddle

Categories

Resources