How to put a comma between arrays in JavaScript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here is a code...
<div id="d1">
<ol>
<li id="li1"></li>
<li id="li2"></li>
</ol>
<div>
<script>
var dod = document.getElementById("d1");
var foo = dod.getElementsByTagName("*");
for(i=0;i<foo.length;i++){
console.log(foo[i].id);
}
</script>
How can I put commas between Id's?

Let's have some fun:
console.log(Array.prototype.map.call(document.querySelectorAll("#d1 *"), function(e) {
return e.id;
}).join(", "));
This was originally meant to be a bit of a joke, but it has a core of seriousness to it and demonstrates some handy things:
document.querySelectorAll will give you a (disconnected) NodeList of elements matching a CSS selector. So #d1 * gives us all of the descendant elements of #d1.
Array.prototype.map is happy to be used on anything array-like, it doesn't require that you use it on an actual array.
Function#call lets you call a function and tell it what this during the function call should be. So Array.prototype.map.call(document.querySelectorAll("#d1 *"), ... calls map making it use the NodeList from querySelectorAll as this.
Array.prototype.map calls the function you give it once for each "array" element, passing in the element, and building a new array from what you return. So our callback that returns e.id tells it to build an array of id values.
Array.prototype.join builds a string from the array elements, using the string you give it as the separator between them.
...and you know from your own code that console.log outputs it.
But looking at your HTML, we need to tweak it to only elements that actually have id values, or we'll end up with a lot of blanks in the result. That's easily done, we just add filter:
console.log(Array.prototype.filter.call(document.querySelectorAll("#d1 [id]"), function(e) {
return e.id !== "";
}).map(function(e) { return e.id; }).join(", "));
Two changes there:
I used #d1 [id] for the selector so we only got back elements with anid attribute.
I added a call to .filter before .map to filter out elements that have an id attribute, but with a blank value (sadly, no way to filter those out in CSS, e.g., defending against <li id="">).
Example

one way would be this:
var separator = ", ";
for(i=0;i<foo.length;i++){
if(i == foo.length - 1) {
separator = "";
}
console.log(foo[i].id + separator);
}

Related

javascript: Create variables/const for all elements in qureySelectorAll [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed last year.
I have multiple in my code, each with class="output" and unique IDs.
<p>Workers: <span class="output" id="workersOutput">0</span><span class="output" id="workersProdOutput"></span></p>
I want to use querySelectorAll to get them addressable in js via variables/const so that I can change their values with textContent.
Individually, I would do the following to find each div, and then the second line to update it on screen.
const workersOutput = document.getElementById('workersOutput');
workersOutput.textContent = `${workers}`;
This is really messy though when I'll have many of these to do (12 at the moment, more to come).
Using querySelectorAll, I can make some hybrid version, using their individual index numbers from the node list. It's not exactly readable or easy to use, as the data attached to each is only visible if I output it somewhere. Not to mentioned if I add more divs, those numbers will change and not be assigned to the same IDs anymore.
const outputs = document.querySelectorAll('.output');
outputs[2].textContent = `${workers}`;
Couldn't I use maybe forEach to create a variable for each using the ID attached to that index number? Or something along the lines of the below example (I know that's not how that works, but I want to get the idea across):
const outputs = document.querySelectorAll('.output');
outputs.forEach((output) => {
const outputs[2] = document.getElementById(output.id);
});
I could also be way off on how to accomplish this the "right way", I'm newish to coding.
Use an object whose property names are the IDs.
const outputs = {};
document.querySelectorAll(".output").forEach(el => outputs[el.id] = el);

Typoglycemia generator [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
My goal is to create a "typoglycemia generator" using HTML CSS JS.
I.e. A web App which takes the user input and mixes up the letters of each word except for the first and last letter.
For example: USER INPUT = "Hello everyone at stackoverflow"; OUTPUT = "Hlelo eevrnyoe at satckoeovrflw"!
I am new to JS, can anyone guide me as to what the steps would be to create this JS code.
Thanks in advance!
Detailed explanation after snippet.
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function Typoglycemia(word) {
var letters=word.split("");
var first=letters.shift();
var last=letters.pop();
var shuffled=shuffle(letters);
shuffled.push(last);
shuffled.unshift(first);
var typoglycemia=shuffled.join("");
return typoglycemia;
}
function TypoglycemiaWord(word) {
document.getElementById("sTypoglycemiaWord").innerText = Typoglycemia(word);
}
function TypoglycemiaSentence(sentence) {
var words=sentence.split(" ");
var typoglycemias=words.map(word=>Typoglycemia(word));
document.getElementById("sTypoglycemiaSentence").innerText = typoglycemias.join(" ");
}
Enter a word: <input onchange="TypoglycemiaWord(this.value)"><br>
Typoglycemia: <span id="sTypoglycemiaWord">result here</span><br>
<br>
Enter a sentence: <input onchange="TypoglycemiaSentence(this.value)"><br>
Typoglycemia: <span id="sTypoglycemiaSentence">result here</span>
First thing we do is remove and save first and last letters.
It's done in function Typoglycemia that takes a word as it's parameter.
We split that word into letters by telling split to split every time it sees "" = nothing = just split.
shift removes the first element of an Array - we store that in first.
pop removes the last element of an Array - we store that in last.
We need a shuffling function - function shuffle - that takes an Array - array as it's parameter.
It goes from last element back to the second - Arrays are zero-indexed, so back to index 1, which is one after index 0 = the first element.
It randomly swaps, goes back, until done, and returns a shuffled array.
Back to Typoglycemia function:
We add last back to the end using push, and first back to the beginning using unshift.
Lastly, we join the array with no spaces "" and return it.
The rest, for word, is simpler HTML and JavaScript.
For sentences, we split by spaced " ", map each word to it's Typoglycemiad value, and then join the result with a space " " between each word.
The rest, for sentence, is simpler HTML and JavaScript.
The rest: Hitting ENTER in an input element calls a function, passing to it the value of itself (this).
TypoglycemiaWord and TypoglycemiaSentence do what they do (as explained above), and send the result to a span element that is found by using it's id in document.getElementById, by setting it's innerText to that result.
Hope this was fun as it was educational!

Regex to replace all occurrences of li tags [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to replace all occurrences of li tags in a string with "\par {\pntext\f1 ''B7\tab}" and then append whatever data was within tags to the end of it.
Basically converting html to rtf format.
e.g
<ul><li>list1 line1</li></ul>
<ul><li><span>list2 line1</span></li></ul>
In the end i want to remove all ul tags
function convertHtmlToRtf(html) {
var richText = html;
richText = richText.replace(/<(?:b|strong)(?:\s+[^>]*)?>/ig, "{\\b\n");
return richText;
}
Your question is a bit broad, but since you say you are using javascript and want a Regex. Then I assume you have a string and want to replace pairs of <li></li> with the given string. Also assuming that your HTML is always very simple and predictable (no <li>s within <li>s), then you could do something like this:
var str = "<ul><li>list1</li></ul>\n<ul><li><span>list2 line1</span></li></ul>";
str.replace(/<li( [^>]*){0,1}>(.*)<\/li>/, "\\par {\\pntext\f1 ''B7\\tab} $2");
Here I'm using a regular expressions that matches a pair of <li> and replace them by that magic string but keeping whatever is inside (note you can easily extend it to also remove the ul if necessary. Ending result:
<ul>\par {\pntext1 ''B7\tab} list1</ul>
<ul>\par {\pntext1 ''B7\tab} <span>list2 line1</span></ul>
Now you can notice right away that it won't remove tags inside - so the <span> will be left there. If you can use jQuery, then it might be easier to convert the nodes correctly than using Regex (which can get quite complicated)
Edit:
Since it's been clarified that jQuery can be used to help on the parsing, then here is a simple example of how you could use it:
https://jsfiddle.net/nazy8sc6/2/
var html = "<ul><li>list1 <b>line1</b></li></ul><ul><li><span>list2 line1</span></li></ul>";
var TAB_STR = "\\par {\\pntext1 ''B7\\tab}";
function convertLi(parent, node) {
var convertedText = TAB_STR + " " + $(node).text() + "<br>";
var convertedNode = $('<span></span>').html(convertedText);
$(parent).append(convertedNode);
}
function convertHtmlToRtf(html) {
var result = $('<span></span>');
$(html).find('li').each((_, node) => {
convertLi(result, $(node));
})
return result.html().replace(/<br \>/g, "\n");
}
var res = convertHtmlToRtf(html);
console.log(res);
In this solution, you simply find all <li> tags and extract the content from it - I keep the original HTML always there and simply copy the converted content into a new HTML from which we finally extract the fully converted text. Hope this helps you, but let me know if I haven't managed to explain myself very well.

Correct use Javascript DOM [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I trying use the Javascript DOM. I need get a information (data-content), searching by class.
The html of website is:
<li class="item info-icon info-icon-phone">
<strong itemprop="telephone" class="phone-place js-expansible-text js-phone-tracker display-phone_ad" data-content="(19) 3879-1066 / (19) 3879-1066" data-style_class="clickable" data-place_id="76588JTY">(19) 3879-1066 / (19) 3879-1066</strong>
</li>
My code doesn't works:
var script = document.getElementsByClass('phone-place js-expansible-text js-phone-tracker display-phone_ad');
var script = document.getElementsByClassName('phone-place js-expansible-text js-phone-tracker display-phone_ad');
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
I believe the function you are looking for is getElementsByClassName.
What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return?
You can retrieve element attributes using the getAttribute() method.
In this instance you could use the following to get the data-content attributes:
var elements = document.getElementsByClassName('phone-place js-expansible-text js-phone-tracker display-phone_ad');
var dataContent = elements[0].getAttribute('data-content');
getElementsByClassName returns an array of matching elements, you could replace this with getElementByClassName with returns a single element, this is preferable if you're only expecting one element. In my example you will see you need to reference the first element in the array elements[0] before calling getAttribute()
Instead with getElementByClassName do the following:
var element = document.getElementByClassName('phone-place js-expansible-text js-phone-tracker display-phone_ad');
var dataContent = element.getAttribute('data-content');
A quick bin to show this in action

How to append javascript varible without using jQuery? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've simple javascript function mentioned below:
<script>
function getValue(val)
{
document.getElementById('answer').value = val;
}
</script>
This function get's called on click of span and returned value gets displayed in input text.
I've three questions:
1] On click of span, if I want to append current value of varible 'val' with previous value; and return appended value to calling function. can you please suggest, how to achieve same without using jQuery?
2] There is one span which is suppose to work like Backspace. So click of span, i want to remove last character from document.getElementById('answer').value [This also without using jQuery]
3] There is one span which is suppose to work like Navigation keys [Right & Left]. So click of span [Let's say right], i want to move cursor position of the input text one character right and similarly for Left [This also without using jQuery]
Can you please suggest some pointers to achieve this?
For your question 1 I think you can do below. Code not tested
function getValue(val)
{
var currentVal = document.getElementById('answer').value
if(currentVal.length > 0 )
currentVal = parseInt(currentVal);
document.getElementById('answer').value = currentVal + val;
}
For question 2 :
Get the value and then do string operation to remove the last char. Its easy little google search for the string operations
For question 3 :
you can use event oncontextmenu for right click. Example below.
How can I capture the right-click event in JavaScript?
For moving cursor check below
Set keyboard caret position in html textbox
+= oprator appends string to existing string(not applicable in this case).
use return keyword to return updated value.
for removing last character use substring.
so try:
function getValue(val)
{
var currentText = document.getElementById('answer').value;
var updatedText = currentText.substring(0,currentText.length-2) + val;
document.getElementById('answer').value = updatedText;
return updatedText;
}

Categories