Adding a javaScript array to a HTML page? - javascript

Im trying to add an array to a webpage. I have tried a few different pieces of code show below but none of them work. I would like the output to be similar to a list like:
text1
text2
text3
...
The code I have used so far is:
var i;
var test = new Array();
test[0] = "text1";
test[1] = "text2";
test[2] = "text3";
// first attempt
$('#here').html(test.join(' '));
// second attempt
$(document).ready(function() {
var testList="";
for (i=0;i<test.length; i++) {
testList+= test[i] + '<br />';
}
$('#here').html('testList');
songList="";
});
I am quite new to javaScript so I am not sure if I have just made a small mistake or if Im doing this in the wrong way. Also, above is a copy of all the code in my javaScript file and some places online are saying I need to import something? Im not sure!
Thanks

Try without quotes:
$('#here').html(testList);
-or-
$('#here').html(test.join('<br />'));
Another approach:
var html = ''; // string
$.each(test,function(i,val){ // loop through array
var newDiv = $('<div/>').html(val); // build a div around each value
html += $('<div>').append(newDiv.clone()).remove().html();
// get the html by
// 1. cloning the object
// 2. wrapping it
// 3. getting that html
// 4. then deleting the wrap
// courtesy of (http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html)
});
$('#here').html(html);
There might be more code in the latter, but it'll be cleaner in the long run if you want to add IDs, classes, or other attributes. Just stick it in a function and amend the jQuery.

Try changing the line
$('#here').html('testList')
to
$('#here').html(testList)

What you have works if you remove the single quotes from testList. However, if you would like an actual unordered list you can do this. (here's a jsFiddle)
var test = new Array();
test[0] = "text1";
test[1] = "text2";
test[2] = "text3";
// first attempt
$('#here').html(test.join(' '));
// second attempt
$(document).ready(function() {
var testList=$("<ul></ul>");
for (var i=0;i<test.length; i++) {
$(testList).append($("<li></li>").text(test[i]));
}
$('#here').html(testList);
songList="";
}); ​

This line:
$('#here').html('testList');
shouldn't have single quotes around testList - you want to use the content of the variable, not the string literal "testList".

Don't pass the variable as a string : $('#here').html('testList'); Pass it without quotes : $('#here').html(testList);

Here's the simplest version:
$(document).ready(function() {
var test = ["text1", "text2", "text3"];
$('#here').html(test.join("<br>"));
});

Related

How can I create a syntax like vue js in vanilla JavaScript?

<div id="">
<span>{{msg}}</span>
</div>
Let's think msg is variable of JavaScript and now I want to get the parent tag of {{msg}} and push a new value by innerHTML, here {{msg}} working as an identity.
demo JavaScript example:
<script>
var msg = "This is update data";
{{msg}}.parentElement.innerHTML=msg;
</scritp>
This is not actual JavaScript code, only for better understanding.
You can use jquery easily to find that element and then replace the text
var msg = "This is update data";
$(`span:contains(${msg})`).html("Its New");
In javascript:
var spanTags = document.getElementsByTagName("span");
var msg = "This is update data";
var found;
for (var i = 0; i < spanTags.length; i++) {
if (spanTags[i].textContent == msg) {
found = spanTags[i];
break;
}
}
Now, you have found that element in found and you can now change its text
if (found) {
found.innerHTML = "New text";
}
The simplest approach is to treat the entire document as a string and then re-parse it when you're done.
The .innerHTML property is both an HTML decompiler and compiler depending on weather you're reading or writing to it. So for example if you have a list of variables that you want to replace in your document you can do:
let vars = {
msg: msg, // pass value as variable
test_number: 10, // pass value as number
test_str: 'hello' // pass value as string
};
let htmlText = document.body.innerHTML;
// find each var (assuming the syntax is {{var_name}})
// and replace with its value:
for (let var in vars) {
let pattern = '\\{\\{\\s*' + var + '\\s*\\}\\}';
let regexp = new RegExp(pattern, 'g'); // 'g' to replace all
htmlText = htmlText.replace(regexp, vars[var]);
}
// Now re-parse the html text and redraw the entire page
document.body.innerHTML = htmlText;
This is a quick, simple but brutal way to implement the {{var}} syntax. As long as you've correctly specified/designed the syntax to make it impossible to appear in the middle of html tags (for example <span {{ msg > hello </ }} span>) then this should be OK.
There may be performance penalties redrawing the entire page but if you're not doing this all the time (animation) then you would generally not notice it. In any case, if you are worried about performance always benchmark your code.
A more subtle way to do this is to only operate on text nodes so we don't accidentally mess up real html tags. The key to doing this is to write your own recursive descent parser. All nodes have a .childNodes attribute and the DOM is strictly a tree (non-cyclic) so we can scan the entire DOM and search for the syntax.
I'm not going to write complete code for this because it can get quite involved but the basic idea is as follows:
const TEXT_NODE = 3;
let vars = {
msg: msg, // pass value as variable
test_number: 10, // pass value as number
test_str: 'hello' // pass value as string
};
function walkAndReplace (node) {
if (node.nodeType === TEXT_NODE) {
let text = node.nodeValue;
// Do what you need to do with text here.
// You can copy the RegExp logic from the example above
// for simple text replacement. If you need to generate
// new DOM elements such as a <span> or <a> then remove
// this node from its .parentNode, generate the necessary
// objects then add them back to the .parentNode
}
else {
if (node.childNodes.length) {
for (let i=0; i<node.childNodes.length; i++) {
walkAndReplace(node.childNodes[i]); // recurse
}
}
}
}
walkAndReplace(document.body);

Filter in AngularJS - text in html tags

I'm not very good at filtering and wanted to write a custom filter based on the following:
I call a service that returns a JSON object with HTML String thats concatenated with another string - so the HTML is funky.
I want to get the text1 and text2 form the following returned HTML string:
<span><b>text1</b><b>text2</b>text3</span>
I have no control how the above is returned to me, but i just wanted to get the two values and concatenate them: text1text2
There is a builtin DOM parser - or you can find a parser in your environment. See on MDN parsing XML and Element. So you could do something like this:
var x = "<span><b>text1</b><b>text2</b>text3</span>";
var oDOM = new DOMParser().parseFromString(x, "text/xml");
var b = oDOM.documentElement.getElementsByTagName("b");
b.length // 2
b[1].innerHTML // text2
HTH
if you just need to strip the html tags, I think you can use the below code
var noHTML = OriginalString.replace(/(<([^>]+)>)/ig,"");
For a filter implementation
angular.module('myNoHtmlFilterApp', [])
.filter('noHtml', function() {
return function(input) {
input = input || '';
var out = input.replace(/(<([^>]+)>)/ig,"");
return out;
};
})
Based on DineSH's answer - I did something like this:
$scope.getTextFromHTML = function(html){
var oDOM = new DOMParser().parseFromString(html, "text/xml");
var b = oDOM.documentElement.getElementsByTagName("b");
return b[0].innerHTML+b[1].innerHTML;
};
I have to pre-define the html string since its not on the DOM yet, like so:
var html = "<span><b></b><b></b></span>";
I will probably add a for loop later in case there is a string I missed, but for now, this is perfect. Thank you for all of your help!

Input array contents into HTML with styles

So I save my array as a variable: var arrayContents = contentData;
and my array: ['content_1', 'content_2', 'content_3', 'content_4']
So i've got my array, I then want to place it into my HTML which i've done via using text like such: $('.container').text(arrayContents);
I need to break my text up so it currently looks like:
And i'm trying to get it to look like :
How can I break my array up so each item drops onto a new line? As when I use .text I print the whole array as one not each separate item.
Use a foreach loop and add a <br> tag to go to next line:
var contentToInsert;
$.each(arrayContents,function(value){
contentToInsert += value + "<br>";
});
$('.container').html(arrayContents);
You need to use html() instead of text(), check this
var htm = '';
var arrayContents = ['content_1','content_2','content_3'];
arrayContents.forEach(function(item){
htm += item + '<br />'; // break after each item
});
$('.container').html(htm);
Actually .text() works with a string value. You passed an array, which leads the "engine" to call arrayContents.toString() to get a string from the array. As you can see there, this function separates each entry by a comma.
If you want to produce an output on one column, you have to generate HTML (as shown in this answer), or editing the div object through javascript DOM functions (fiddle) :
for (var i = 0; i < arrayContents.length; i++) {
var currentElement = document.createElement("DIV"); // "DIV" or block-type element
var currentText = document.createTextNode(arrayContents[i]);
currentElement.appendChild(currentText);
document.getElementById("container").appendChild(currentElement);
}
Be sure of what kind of HTML you want to produce.

Getting Word Anywhere from Textarea

I am trying to use a variable of a textareas value but I don't want the entire value only the new word that is being written.
What I've tried doing is something like this-
function getValue(ele,array){
var a = ele.val();
array.push(a);
}
function newWord(ele,array){
var b =ele.val();
array.toString.match(b);
}
$(function() {
$('#textarea').keyup(function() {
var array = [];
getValue($(this),array);
console.log(array);
var c = newWord($(this),array);
console.log(c);
});
});
What I was hoping for is that it would get the newly typed word. All I want to do is get that new word that is being typed up until a space is entered. And I was working with a few plugins that would getSelection for all modern browsers and well that just didn't work for me as well.
Does anyone have a suggestion on the best way to do this? I don't mind on keep trying myself just need a little hand to lead me on the right path to get my full code working the way I need it to. Full Code is here http://jsbin.com/obihig/1/edit it is a Auto Suggestion, for textarea, and it needs to be for every word being written.
$(function() {
$('#textarea').keyup(function() {
var array = [];
var newWord;
array = this.val().split(' ');
console.log(array);
newWord = array[array.length - 1]
console.log(newWord);
});
});

How can I assign null value to an array element?

I am facing too small problem, could you give me idea how to solve that.
for(var j=cArray.length-1;j>=0;j--)
{
if(cArray[j]=='.') {
cArray[j]='';
break;
}
else{
cArray[j]='';
}
}
I wrote this for loop in javascript.NULL value is not assigning to array element.
At last i am getting what is the content in cArray[j] only.I can't able to change that value.My declaration is correct or not?
What are you trying to accomplish?
What the code does in this form is that it makes all elements in an array '' (empty) that are after the last '.' element.
If you just want to truncate the array you could do somethink like this:
var jsArray = ['H','e','l','l','o','.','w','o','r','l','d'];
jsArray.length = 5;
alert(jsArray.length); // returns 5
Your code is right. Maybe it is empty? See my demo and observe as it works =)
To truncate the array at the first .:
for(var j=cArray.length-1;j>=0;j--)
{
if(cArray[j]=='.') {
cArray.length = j;
break;
}
}
Or, if the array is really just a string:
var myString = "1.1.1";
var result = myString.split(".");
var firstPart = result[0];
firstPart now contains 1.

Categories