Change string (text-element) in svg-element - javascript

I'm just playing around with some svg-drawings.
Actually I have a svg-drawing, that contains some grouped Elements.
I like to copy one of These Elements and give it e new value in its Text-field.
First I copy the Element:
var selectedSymbol = document.getElementsByClassName('selected');
if(selectedSymbol.length >>0)
{
var newSymbol = selectedSymbol[0].cloneNode(true);
//now Change Information of <text id='BMK'>emptyBMK</text>
}
Of course every grouped Symbol has this text-field, with same id, so I think I Need to Change it only in selected Symbol but newSymbol.getElementsById('BMK') does not work :(

Ok, I did it, but I am not sure if this is a good practice:
for (var x = 0; x < newSymbol.childElementCount; x++)
{
if(newSymbol.Children[x].id == "BMK")
newSymbol.children[x].innerHTML = "newBMK";
}
Can someone tell me if this is ok?
I mean it works but seems a bit strange to me.

Related

Apps Script JS adding items to array from range (if not already in array) fails

I am looping through various cells and want to add their string content do an array, if the content is not already in the array. It works perfectly fine when I do it manually like so, trying to add 'eJobs' to the array (see below "var item = 'eJobs') which already containts 'eJobs':
var divisionarray = ['eJobs']
for (var i = 0; i < cells_users.length-1; ++i) {
var row_users = cells_users[i];
if (row_users[0] == user_ldap) {
var podarray = row_users[1].split(', ')
for (j = 0; j < podarray.length; j++) {
for (var k = 0; k < cells_edit.length; ++k) {
var row_edit = cells_edit[k]
if (podarray[j] === row_edit[0]) {
var item = 'eJobs'
if (!(divisionarray.indexOf(item) >= 0)) {
divisionarray.push(item)
}
}
}
}
Logger.log(divisionarray)
As expected, the log file shows [17-10-08 19:11:04:111 BST] [eJobs], illustrating that the code works and 'eJobs' has not been added to the array as it is already in the array.
Now, when I change var item='eJobs' to values of a range
var item = sheet_pods_edit.getRange(startRow+k, startColumn+1).getValue();
the code does not work anylonger, as the log file shows:
[17-10-08 19:14:03:770 BST] [eJobs, eJobs, BestJobs, Vivre Deco, ...
Note I have a range of thousands of cells, so I get alot of duplicates added. What am I missing? Note the cells of the defined range are indeed just strings with a single word (e.g. 'eJobs').
The code is working and the log file is indicating what the problem is..
[eJobs, eJobs, BestJobs, Vivre Deco,
In the second eJobs there is a white space before eJobs, so the first value and the second value don't match.
Without seeing your data and going by the 'just strings with a single word' I would say that using a .replace(" ", "") on the text string should work, this will find the first " " in the string and remove it. I.e. " eJobs" would become "eJobs".
2.
Is this line of code just for testing? You should never use a method like this in a script. It will be extremely inefficient
var item = sheet_pods_edit.getRange(startRow+k, startColumn+1).getValue();
Instead get the full range using .getValues()and iterate over it then.
3.
Is there a reason you are using === in if (podarray[j] === row_edit[0]) unless you need to check for type always use ==

Javascript - Clone a div after user input on quantity

I'm trying to clone a div after a user puts in the amount of divs to be cloned. User will put in a number (say 3) and the function will create three group-container divs. The prompt works, but nothing happens after that. Seems pretty simple but it's evading me. Is my logic incorrect? Obviously my programming skills are very new.
I create a function that has the input (groupInput)
Create a for loop to reiterate the following instruction
The for loop will clone group-container as many times as i<groupInput
function addGroup() {
var groupInput = prompt("How many groups? 1-100");
for(i=0; i<groupInput; i++){
var group = document.getElementById("group-container");
var clone = group.cloneNode(true);
group.parentNode.appendChild(clone);
}
}
Any suggestions would be much appreciated.
Updated
Thanks for the suggestions, I get I should use class for this now.
I did get it to work with the ID in jsfiddle (not sure why it's not in my html), but now with the class it's not: https://jsfiddle.net/waynebunch/c5sw5dxu/. getElementsByClassName is valid right?
You should put the group declaration outside of the for loop so the clone remains the same throughout the loop.
Fiddle
function addGroup() {
var groupInput = prompt("How many groups? 1-100");
var group = document.getElementById("group-container");
for(i=0; i<groupInput; i++){
var clone = group.cloneNode(true);
group.parentNode.appendChild(clone);
}
}
The prompt() method probably returns the correct number, but with type set to String. Instead try
parseInt(groupInput)
To convert the value to a number, which should allow the for loop to execute properly.
Something like the below might work once you get your quantity in from a prompt or text input.
var doc = document;
var input = prompt("Please enter your qty", "0");
if (input != null) {
for (i = 0; i < input; i++) {
var elem = doc.createElement('div');
elem.className = 'group-container';
}
}

how to remove HTML tags from a string in JavaScript without using regexp?

I am new to programming and I was solving this exercise.
I have tried 3 loops with string.slice() but for some reason it prints an empty string.
Would you please explain what happens inside my code and why it prints the wrong output and how I can correct, rather than giving me your version of the correct answer, so that I can learn from my mistakes.
the test input is
<p><strong><em>PHP Exercises</em></strong></p>
and output should be PHP Exercises
p.s this is not a PHP exercise, I'm not confused
here is my code :
function remove(answer){
var sen = answer.split("");
var arr = [];
for (var i = 0; i<answer.length; i++){
if (answer[i] == "<"){
for (var j = i; j<answer.length; j++){
if (answer[j] == ">"){
for (var k = j; k<answer.length; k++){
if (answer[k] == "<"){
return answer.slice(j+1, k);
}
}
}
}
}
}
}
Try this:
function stripTags(data)
{
var tmpElement = document.createElement("div");
tmpElement.innerHTML = data;
return tmpElement.textContent || tmpElement.innerText || "";
}
var something = '<p><strong><em>PHP Exercises</em></strong></p>';
alert(stripTags(something));
or You can use string.js (string.js link):
var S = window.S;
var something = '<p><strong><em>PHP Exercises</em></strong></p>';
something = S(something).stripTags().s;
alert(something);
<script src="https://raw.githubusercontent.com/jprichardson/string.js/master/dist/string.min.js"></script>
if You're trying nodejs so:
var S = require('string');
var something = '<p><strong><em>PHP Exercises</em></strong></p>';
something = S(something).stripTags().s;
console.log(something);
As to why the provided code isn't working, the code returns when j = 2 and k = 3. I discovered this by writing console.log(j, k); immediately before the return. This insight made it clear that the code is identifying the first set of open tags, when actually you seem to want to identify the open and closed "em" tags. The answers provided by others are more robust, but a quick fix to your code is:
change
if (answer[i] == "<"){
to
if (answer.slice(i, i+3) == "<em"){
Hope this helps!
Your code does not account for ... nothing. It simply stops at the first encounter of what's between ">" and "<", which is, in the first case, is nothing! You should check if a character is present, and move on if not.
Honestly, this is one of those useless exercises that text books use to try to get you to think outside the box. But you will never want to loop through a string to find text between tags. There are so many methods built in to JavaScript, it's literally reinventing the wheel to do this... that is if a wheel were really a for-loop.
If you really want to avoid Regex and other built in functions so that you can learn to problem solve the long way, well try slicing by brackets first!

Parse two HTML String with JS - and convert one to Int

I'm currently parsing the first string already and everything works fine:
var links = document.getElementsByTagName("a");
var element;
function search() {
for (var i = 0; i < links.length; i++) {
element = links[i];
var price = parseInt(element);
if (element.href.indexOf("http://www.myurl.com") == 0) {
//program goes here
}
}
}
However, each of the hyperlinks (products) has another string with the price on it (in the same div element). This would look like this:
<span class="price_table_value">
Pricetag:<br>
<span style="color:white">239,--€ </span>
</span>
I would love to somehow parse that too and use parseInt() to make an Integer out of it.
I've thinking about this for a hour and cant find a good solution (im still beginning to learn JS). Any help/ideas?
You can try this one...
function search() {
for (var i = 0; i < links.length; i++) {
element = links[i];
var price =parseInt($(".price_table_value").value);
}
}
Just other example without jQuery:
var priceHolder = Array.prototype.slice.call(document.querySelectorAll(".price_table_value span"));
priceHolder.forEach(function(item) {
var price = /([0-9]+[.0-9]?)/.test(item.innerHTML) ? parseFloat(RegExp.$1) : 0;
console.log(price);
});
Here is working jsfiddle:
http://jsfiddle.net/zono/9gL1vw0e/9/
Try to go with something like in this fiddle?
Basically, this should go in you loop body, but replace the [0] with i, and add the logic you need:
var rawPrice = $(element).children('.price_table_value').children('span').text();
var price = parseFloat(rawPrice);
Of course only do it if you're 100% certain the price format will start with the price value (parseFloat will trim anything trailing the number, just as King Kong noticed). Also, you may want to wrap it around a try/catch block (and best always do it when parsing).
Please note that generally, you probably should be getting such values from some sort of API, not just getting these from DOM elements like this, so please make sure that's what you want to do.

JavaScript array.sort() Issue

drafting up a quick listing tool to list local kids baseball teams. Takes a couple of inputs and writes to a text field. There's some validation and whatnot too, but that's out of scope and doesn't seem to be impacting things.
Problem is, I'm having trouble figuring out how to "capture" the existing text, add the new inputs and sort the whole lot, before writing the new result to the paragraph element (effectively replacing it).
So far I have:
var LeagueTeams = [];
var IndividualTeam = '';
LeagueTeams.push(document.forms[0].TeamName.value);
LeagueTeams.push(document.getElementById('TeamList')
LeagueTeams = LeagueTeams.sort();
for (j = 0; j < LeagueTeams.length; j++) {
IndividualTeam = LeagueTeams.pop();
IndividualTeam = IndividualTeam + '' + \n;
document.forms[0].TeamName.value += IndividualTeam;
}
What I end up getting is my input, and then an array of my input PLUS the previous contents, with a couple of line breaks. Setting the operator to = instead of =+ stops it from printing to the array at all.
i.e.
Enter: a
Text area: a
Then enter: b
Text area: a ab
(etc)
OK, now that we have a better idea of what you're trying to do, here's some code that will do that:
HTML:
<label>Enter Team Name: <input id="newTeam" type="text"></label>
<button id="add">Add</button><br>
All Teams:<br>
<textarea id="allTeams" rows="40" cols="40"></textarea>
Javascript (plain javascript, no framework, called after page is loaded):
var teamList = ["Dodgers", "Mets", "Giants"];
document.getElementById("add").onclick = function() {
var input = document.getElementById("newTeam");
if (input.value) {
teamList.push(input.value);
}
updateTeamList();
input.value = "";
}
function updateTeamList() {
teamList.sort();
var o = document.getElementById("allTeams");
o.value = teamList.join("\n");
}
updateTeamList();
And, you can see it working here: http://jsfiddle.net/jfriend00/HkhsL/
Comments on your existing code:
I'm not sure I understand what you're trying to do overall, but do you realize that this loop is going to have problems:
for (j = 0; j < LeagueTeams.length; j++) {
IndividualTeam = LeagueTeams.pop();
IndividualTeam = IndividualTeam + '' + \n;
document.forms[0].TeamName.value += IndividualTeam;
}
Each time you do LeagueTeams.pop() you are reducing the length of the array and you're continually comparing to LeagueTeams.length in the for loop. This will only get half way through the array because each time through the loop, you increment j and decrement LeagueTeams.length which means you'll only get half way through the array.
If you intend to iterate all the way through the array in your for loop, you should use this version that gets the length once initially and simplifies the code in the loop:
for (j = 0, len = LeagueTeams.length; j < len; j++) {
document.forms[0].TeamName.value += LeagueTeams.pop() + '\n';
}
or perhaps even better, this version that doesn't even use j:
while (LeagueTeams.length > 0) {
document.forms[0].TeamName.value += LeagueTeams.pop() + '\n';
}
Then further, I see that you're trying to use LeagueTeams.sort() on an array that has both strings in it and DOM object references. What are you trying to do with that sort because the built-in sort function does a lexigraphical sort (e.g. alpha) which will do something odd with a DOM reference (probably sort by whatever toString() returns which may be object type)?
If you want to sort the input by team name, then you would need to put both team name and the DOM reference into an object, insert that object into the array as one unit and then use a custom sort function that would sort by the name in the object. As your code is written above, you see to be using document.getElementById('TeamList') which is the same for all teams so I'm not sure why you're putting it into the array at all.
If you can show your HTML and a more complete version of your code, we could help further. What you have above is just a non-working piece of code and we don't know what your HTML looks like that it's trying to operate on.
FYI, there are several syntax errors in the code you posted, so this can't be running code:
Missing paren at the end of this: LeagueTeams.push(document.getElementById('TeamList'))
Missing quotes around \n: IndividualTeam = IndividualTeam + '' + '\n';
If you are just trying to make a list of the teams, try something like:
<script type="text/javascript">
function addTeam(form) {
var para = document.getElementById('teamList');
var teams = para.innerHTML.split(/<br\s*[\\]?>/);
teams.push(form.teamName.value);
para.innerHTML = teams.sort().join('<br>');
}
</script>
<form action="">
<input type="text" name="teamName">
<input type="button" value="Add team" onclick="addTeam(this.form)">
</form>
<p id="teamList"></p>
You may be using different elements or layout, but the strategy should be about the same. If you are making a set of options for a select, things are a little easier.

Categories