Can this big block of code be avoided in javascript? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Haven't worked much on front-end and was wondering if what I did is correct.
I have created an html table that displays data.
I have added button and check-boxes to modify structurally the table i.e. add a row.
The code to do that is a big block of code that does something like:
var table = document.getElementById('table');
table.insertRow(1);
var id_td = document.createElement('td');
//create options element
id_td.appendChild(options);
var name_td = document.createElement('td');
//create input textbox
name_td.appendChild(txt_box);
etc etc
So I don't like the fact that it is a really big-block of essentially repeating code that creates the elements.
I wanted to know, am I on the right track? Is this the only way unless we use some library like JQuery?

The VanillaJS approach
You can use something like
var table = document.getElementById('table');
table.innerHTML = "<tr><td id="+id+"></td><td class="name"></tr>";
To add your markup as a string, which might end up being more clear. Tough to tell exactly without seeing exactly how you're repeating yourself, but you might be able to abstract this out into a function
Libraries
There are plenty of libraries though that abstract away this ugliness though. jQuery is one, but something like knockoutjs might be a better fit for you.
It allows you to define a data model and bind html templates to that data model with automatic updating. So you could then just define your data as a JSON object and have it reflected in the DOM, with future updates just touching the view-model object and not having to deal with the DOM functions at all.

I don't like the fact that it is a really big-block of essentially repeating code that creates the elements
Why not make aliases for the long-winded function names?
var gid = function (id) {return document.getElementById(id);}, // so short!
ce = function (e) {return document.createElement(e)}, // ce(tag) is easy!
td = function () {return ce('td');}, // td() now makes a new `<td>`
ap = function (p, c) {return p.appendChild(c), p;}; // return more useful
now that "big-block" is
var table = gid('table'),
row = table.insertRow(1);
var id_td = td(), options = ce('select');
ap(id_td, options);
var name_td = td(), txt_box = ce('textarea');
ap(name_td, txt_box);
// etc etc

Related

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.

Javascript element html without children [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
In my javascript code I need to get the definition of an element, but without its content - neither text nor children.
E.g. for:
<div id="my_example_id" class="ShinyClass">
My important text
<span> Here</span>
</div>
I would like to write a javascript fucntion that when provided with the element of the div above will return the following as string:
<div id="my_example_id" class="ShinyClass">
I have been trying with different manipulations over the elements, functions like innerHTML, outerHTML and similar, but I was unable to figure out how to fetch only the part I am interested in. Is substring until the first > the best possible solution?
EDIT: selecting the element is not part of the question - I know how to do that, no prob. Rather the question is: when I have already selected a particular element how to parse as string only its own definition.
UPDATE:
const div = document.getElementById('my_example_id'); // get the node
const html = div.outerHTML.replace(div.innerHTML || '', ''); // simple set logic
console.log(html);
Just some way to do this, not saying the best.
const div = document.getElementById('my_example_id');
const copy = div.cloneNode(true);
const parent = document.createElement('div');
copy.innerHTML = '';
parent.appendChild(copy); // I forgot to add this line.
const html = parent.innerHTML;
console.log(html);
Basically you create a copy of the div, create a parent, then remove innerHTML of the copied node to leave out just the 'div' itself. Append the copied node to the new parent and show the parent's innerHTML which is just the 'div' you wanted.
you don't need to do all that fancy stuff copying it to a parent..
// make a copy of the element
var clone = document.getElementById('my_example_id').cloneNode(true);
// empty all the contents of the copy
clone.innerHTML = "";
// get the outer html of the copy
var definition = clone.outerHTML;
console.log(definition);
I threw it in a function in this fiddle: https://jsfiddle.net/vtgx3790/1/
I guess that a Regex is what you need. Check if this works for you
function getHtml(selector) {
var element = document.querySelector(selector)
var htmlText = element.outerHTML
var start = htmlText.search(/</)
var end = htmlText.search(/>/)
return htmlText.substr(start, end + 1)
}
alert(getHtml('.ShinyClass'))
example here
console.log(getElementTag("my_example_id"));
function getElementTag(myElementId) {
var FullEelementObject = document.getElementById(myElementId);
var FullElementText = FullEelementObject.outerHTML;
var regExTag = new RegExp(/(<).*(>)/i);
openingTag = FullElementText.match(regExTag);
return openingTag[0];
}
Just threw together this JSFiddle, it gets the outerHTML of the element you pass the function, the regExp to get the full opening tag.
Edit: Here is the JSFiddle

converting python code to javascript code [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 7 years ago.
Improve this question
can somebody help for my code which is written in python, i want to write it in javascript but im in trouble, i dont know how.
python code
cities={}
for line in open("linnadkaugustega.txt", "r", encoding="UTF-8"):
m=line.strip().split()
abim=[word.split(":") for word in m[1:]]
cities[m[0]]={}
for couple in abim:
cities[m[0]][couple[0]]=int(couple[1])
print(cities);
and i tried in javascript but that doesen't work
function tere(){
console.log("Tere");
$.get('read.txt', function(data) {
cities={};
var lines = (data.trim()).split();
abim=[var word.split(":") for word in m[1:]]
cities[m[0]]={};
for var couple in abim
cities[m[0]][couple[0]]=couple[1];
console.log(cities);
}, 'text');
}
tere();
can somebody help me ?
You have syntax issues translating from python to js. Heres how arrays work...
if you have an array litteral in javascript
var cities = [];
Then we would add to the array by calling push
cities.push('Portland');
...
cities.push('New York');
we can then iterate over the array by calling forEach on the array object.
cities.forEach(function (city, index){
//do work on each city
console.log(city);
});
// Portland
// New York
A few things:
.split() in JS does something different than split in python when no separator is given. To split a line into words, you'll need to split on whitespaces explicitly
you're missing the for loop over the lines of the file. Python uses the iterator syntax for reading from the file, in JavaScript an ajax request loads the whole file and you'll need to split it in lines yourself.
JavaScript does not have that m[1:] syntax, you'll need to use the .slice() method instead
JavaScript does not have array/list comprehensions. You will need to use an explicit loop, or the map method of arrays
your loop syntax is too pythonic. In JavaScript, for loops need parenthesis and an index variable.
So this should do (supposed you have the jQuery library loaded and it finds the file):
$.get('read.txt', function(data) {
var cities = {};
var lines = data.split("\n");
for (var i=0; i<lines.length; i++) {
var line = lines[i];
var m = line.trim().split(/\s+/);
var abim = m.slice(1).map(function(word) {
return word.split(":");
});
var obj = cities[m[0]] = {};
for (var j=0; j<abim.length; j++) {
var couple = abim[j];
obj[couple[0]] = couple[1];
}
}
console.log(cities);
}, 'text');

How to switch <td> content with another <td> [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 8 years ago.
Improve this question
So the thing goes as following: I'm a begginer programmer (so far i know HTML, CSS some JavaScript and some C++) and we have a school project to create a chessboard with figures on them but I want to go a step further and be able to move the figures.
So far I've used the prompt function to get the coordinates and move them around but that feels far too much stone-agish. Now what I wish to accomplish is to be able to click on a , copy its content into a variable and upon clicking on another replace its content with the one stored in the variable. (I'll deal with the rules later..)
Each has its unique id and I have used element.firstChild.nodeValue to acquire the content.. Any suggestions on how to do this in JavaScript without using jQuery (if it can't be done in JavaScript then by all means do it in some other language.. it's about time I start learning them anyway.. :P)
If each <td> has a unique id, what about:
var lastStoredValue = "", lastClicked = ""; // = "" is important in that case
var t1 = document.getElementById("t1"); // td with id="t1"
var t2 = document.getElementById("t2"); // td with id="t2"
t1.onclick = function() {
if (lastClicked !== "t1" && lastStoredValue.trim())
t1.innerHTML = lastStoredValue; // replace its content with the one stored in the variable
if (!lastStoredValue.match(new RegExp(t1.innerHTML)))
lastStoredValue= t1.innerHTML; // copy its content into a variable
lastClicked = "t1";
}
t2.onclick = function() {
if (lastClicked !== "t2" && lastStoredValue.trim())
t2.innerHTML = lastStoredValue; // replace its content with the one stored in the variable
if (!lastStoredValue.match(new RegExp(t2.innerHTML)))
lastStoredValue= t2.innerHTML; // copy its content into a variable
lastClicked = "t2";
}
This gets what is stored into one td and puts it into a variable; then stores what is in the variable into another td when click on that td.

Good practice when manipulating HTML controls via Javascript [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What is a good way to manipulating HTML controls?
By creating HTML element?
var select = document.getElementById("MyList");
var options = ["1", "2", "3", "4", "5"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.Text = opt;
el.value = opt;
el.innerHTML = opt;
select.appendChild(el);
}
Or by manipulating HTML:
var options = new Array(2);
options [0] = '1';
options [1] = '2';
options [0] = '<option>' + options [0] + '</option>';
options [1] = '<option>' + options [1] + '</option>';
var newHTML = '<select>' + options [0] + options [1] + '</select>';
selectList.innerHTML = newHTML;
Which one of these is a good practice? Is one preferred over other in specific conditions?
1st approach looks more modular and reusable. You may want to put the lines within for loop in a method and call that method.
Always 1st approach. if you are using innerhtml style, browser is creating itself.
The first method is better than the second one , i.e.,
**Creating an HTML element is better than manipulating the DOM"
The reason: being working with DOM can cause browser reflow.
For example : assume you need to replace an element to the DOM which already exists.
Using approach :
Creating a DOM Element : You create an element. Add verious attributes to it and replace it. The element will be added in one go and there will be only one reflow of the document.
Manipulating DOM : You need to add and remove attributes or elements one by one. This may cause the browser to trigger a reflow for all the elements and attributes that are being manipulated. This will take up valuable resources in rendering the flow of the document as the elements are manipulated.
So creating a dom element is much smoother since your browser wont have to render the flow of the document again.
*EDIT : * If you need to insert many elements then the best approach is to create a Document Fragment. The document fragment is in memory and not part of the DOM tree. Thus adding elements to it DOES NOT cause reflows. As the documentations says :
Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Consequently, using document fragments often results in better performance.

Categories