How to convert HTMLCollection to string - javascript

I'am working on a bot that will edit some form on website, one part of the form is where is some html. I copy data from the converting to HTMLCollection do some actions, and then i want to save it back to the . And in case to do so i need to convert HTMLCollection object back to a string.
How i get and convert the data:
var htmlFromTextArea = document.getElementById('nameOfTextArea').value;
var htmlObject = document.createElement('div');
htmlObject.innerHTML = htmlFromTextArea;
var htmlElements = htmlObject.getElementsByTagName("*")
And now i need htmlElements to become string again
I tried the following but it seems not working:
var stringWithHtmlTobeSavedInTextArea = htmlElements.text;
or
var stringWithHtmlTobeSavedInTextArea = htmlElements.textContent;
or
var stringWithHtmlTobeSavedInTextArea = htmlElements.innerText;

Yes, htmlElements is HTMLCollection. So seperate each element and add outerHTML of element to string using loop.
var htmlObject = document.createElement('div');
htmlObject.innerHTML = "<a>anchor</a><p>paragraph</p>";
var htmlElements = htmlObject.getElementsByTagName("*");
var stringWithHtmlTobeSavedInTextArea="";
for (i = 0; i < htmlElements.length ; i++){
stringWithHtmlTobeSavedInTextArea += htmlElements[i].outerHTML;
}
console.log(stringWithHtmlTobeSavedInTextArea);
Please note that, above solution is not correctly working in case if the HTML inside div element is like <div><a>anchor</a></div>
So It is better to use innerHTML or get actual text from <textarea> eg.
var stringWithHtmlTobeSavedInTextArea = htmlObject.innerHTML;
//Or
var stringWithHtmlTobeSavedInTextArea = htmlFromTextArea;

Related

Array is not an array anymore after getting stringified and parsed (JSON)

After that I stringified my array I parsed it, I then tried to acces one of the elements inside the array (array[number]) but it seems that the elements in the array are all mashed as one or something like that. I would like to know why and how to change this. Thanks in advance!
var linkrecup = localStorage.getItem('linksstring');
JSON.parse(linkrecup);
alert(linkrecup);
var linkarr = [''+linkrecup+''];
alert(linkarr.length); // this gives '1'
var div = document.createElement('div');
document.body.appendChild(div);
div.id = 'placememe'+memenumber+'';
div.className = 'meme';
var nombrememes = document.getElementsByClassName("meme").length;
alert(nombrememes);
var crpt = nombrememes - 1;
alert(crpt);
alert(linkarr[3]); // this gives 'undefined'
Every var that is used is declared in another piece of code, if you want it just ask and I'll gladly give it to you.
EDIT: So basically what im doing (trying) with this code to do is to push a link that is given by the user (prompt) and add it to the array of links that already have some links stored in (.push) then stock it (the whole array) in localStorage (stringified with JSON.stringify) then re-acces this array later (with a localStorage.getItem) then parse it (JSON.parse) and then use one of the elements of the array (link) as the link for an image. Here's the code with the stringify and shit.
var newmeme = prompt('Please paste the link of the meme below!');
memes.push ('placememe'+memenumber+'');
links.push (newmeme);
var div = document.createElement('div');
document.body.appendChild(div);
div.id = 'placememe'+memenumber+'';
div.className = 'meme';
var nombrememes = document.getElementsByClassName("meme").length;
var vrb = nombrememes - 1;
div.innerHTML = '<img src="'+links[vrb]+'" width="700" height="700" alt="" />';
var linksstring = links
localStorage.setItem('linksstring',JSON.stringify(linksstring));
var linkrecup = localStorage.getItem('linksstring');
JSON.parse(linkrecup);
alert(linkrecup);
JSON.parse(object) returns a parsed object
Try using
var parsedlinkrecup=JSON.parse(linkrecup)

inserting text-field to table cell using javascript

I am making a program in which I want to add an input field to a table cell.
Look at the code below:
var arr_title = ["song","artist","genre"];
for (var title in arr_title){
var newl = document.createElement("input");
newl.id = 'edit_text';
var newf = "td_" + arr_title[title];
newf.appendChild(newl);
}
newf gets the value of td_song,td_artist etc and these are already defined as:
var td_song = document.createElement("td");
var td_artist = document.createElement("td");
var td_genre = document.createElement("td");
in the same function and then I've appended them to a table and it works fine
but when I am creating the input element then there's an error:
Uncaught TypeError: newf.appendChild is not a function
I know it has no end tag and it needs to be in a form element, but the error is same when I try to add any other element.
Help!
the value stored in newf is a string, not a DOM element; appendChild is not a valid method on strings. Just because the string value stored in newf matches the name of a variable you created (td_song, etc), does not mean it is now a handle to that element. You would be better of storing your created elements in an object, keyed off of that value:
var elems = {
td_song: document.createElement("td"),
td_artist: document.createElement("td"),
td_genre: document.createElement("td")
};
var arr_title = ["song","artist","genre"];
for (var title in arr_title){
var newl = document.createElement("input");
newl.id = 'edit_text';
var newf = "td_" + arr_title[title];
elems[newf].appendChild(newl);
}
After this line, the contents of newf is simply a string reading "td_song" for example.
var newf = "td_" + arr_title[title];
You are probably getting a JS error of "newf is not a function" ?
If you want newf to really be the one of those vars, you could explore using eval()
var newf = eval("td_" + arr_title[title]);
Does the <td> you're trying to append to have an ID of "td_" + arr_title[title]?
If so, you need to do...
var newf = document.getElementById("td_" + arr_title[title]);
newf.appendChild(newl);
newf is a string and you can't append child to string, if you want to refer to the variable with this name you should use window :
window[newf].appendChild(newl);
Hope this helps.

Jquery ID selector doesnt work with a variable

I've read a billion questions like this, but never found an answer yet.
Anyway, when I type
var variableContainingID = "header";
var div = $("#"+variableContainingID);
It returns 'undefined'
But when I type
var variableContainingID = "header";
var div = $('[id^="'+variableContainingID+'"]');
It works fine.
Any ideas why?
UPDATE
var json = '{"divs":['
var children = $(".parent_container > div");
var idArray = [];
var numArray = [];
for (var x=0; x<children.length; x++) {
var eleid = $(children[x]).attr("id");
idArray.push('"'+eleid+'"');
numArray.push(x+1);
}
var idString = idArray.join(",");
var numString = numArray.join(",");
json += idString;
json += '],"number":['+numString+']}';
var obj = JSON.parse(json);
for (x in obj["divs"]) {
var div = $('[id^="'+obj["divs"][x]+'"]');
}
Do you think the double quotes could be throwing it off?
As you wrote in your question:
var div = $("#"+variableContainingID);
var div = $('[id^="'+variableContainingID+'"]');
These two lines are not identical. The first one, will select an element with id of header. The second one,
selects elements that have the specified id with a value beginning exactly with a given string (header).
So if you have an element like this:
<div id="headerHere"></div>
The first one ($("#"+variableContainingID)) can't select it, but the second one ($('[id^="'+variableContainingID+'"]')) can select that element.
This is because you used ^= in your selector. See jQuery API: Attribute Starts With Selector (name^="value").
It's worth to see all attribute selectors in jQuery.
Attribute Selectors in jQuery

get the text of a div

I have been trying to get the text from a div using only javascript.
I started with jQuery using the following code:
var divText = $("div.Xr3").html();
Then for my JavaScript I tried:
var divText = document.getElementsByClassName("Xr3").innerHtml;
Which returns undefined. How can I accomplish this using JavaScript only?
getElementsByClassName returns a live array of HTML elements, so you can't access innerHTML directly like this. You will either have to loop over its results, or if you know there's only one, apply [0] to it before accessing innerHTML.
var divTexts = [];
var divs = document.getElementsByClassName("Xr3");
var numDivs = divs.length;
while (var i = 0; i < numDivs; i++) {
divTexts.push(divs[i].innerHtml);
}
or, in a single-element scenario,
var divText = document.getElementsByClassName("Xr3")[0].innerHtml;
If Xr3 is used one time, you can use
var divText = document.getElementsByClassName("Xr3")[0].innerHtml;

How to wrap dynamically selected ids using jquery or javascript

I am working on a project in Google Blogger. First i want to explain a thing.
In blogger every post that is created has a unique id assigned to it by blogger itself. This id can be retrieved using Blogger JSON. So i have retrieved the ids of four recent posts using JSON.
I want to wrap these first four id containers around a DIV container using JQuery or Javascript.
The problem is when i use these ids absolutely in the selector $ and use the wrapAll() function the id container's gets wrapped up. But as i said i'm using JSON to get the container id's so the values of ID's are stored in variable's and when i use those variable as selection for wrapAll() function it doesn't work.
I have demos of both those situation's which can be seen by going to this blog http://youblog-demo.blogspot.com/ and using the firebug console to run these code.
Situation 1 when i use absolute container ids
var script = document.createElement("script");
script.src = "http://youblog-demo.blogspot.com/feeds/posts/default?alt=json&callback=hello";
document.body.appendChild(script);
function hello(json){
if(json.feed.entry.length>4){
var post_num=4;
var id_coll = new Array();
for(i=0; i<post_num; i++){
var ids = json.feed.entry[i].id.$t;
var post_id = ids.substring(ids.indexOf("post-"));
var only_id = post_id.substring(5);
id_coll[i] = only_id;
}
$("#3337831342896423186,#123892177945256656,#9095347670334802803,#2525451832509945787").wrapAll('<div>');
}
};
Situation 2 when i use variable's to select the containers
var script = document.createElement("script");
script.src = "http://youblog-demo.blogspot.com/feeds/posts/default?alt=json&callback=hello";
document.body.appendChild(script);
function hello(json){
if(json.feed.entry.length>4){
var post_num=4;
var id_coll = new Array();
var front_name = "#";
for(i=0; i<post_num; i++){
var ids = json.feed.entry[i].id.$t;
var post_id = ids.substring(ids.indexOf("post-"));
var only_id = post_id.substring(5);
id_coll[i] = only_id;
}
var joined_id_0 = String.concat(front_name,id_coll[0]);
var joined_id_1 = String.concat(front_name,id_coll[1]);
var joined_id_2 = String.concat(front_name,id_coll[2]);
var joined_id_3 = String.concat(front_name,id_coll[3]);
$(joined_id_0,joined_id_1,joined_id_2,joined_id_3).wrapAll('<div>');
}
};
So when i use the situation 2 code then it doesn't work but the situation1 code works fine. Can anybody help me with this
You need to pass in the selector as a string, not a list of arguments;
$(joined_id_0+', '+joined_id_1+', '+joined_id_2+', '+joined_id_3).wrapAll('<div>');
Or even better, replace all of:
var joined_id_0 = String.concat(front_name,id_coll[0]);
var joined_id_1 = String.concat(front_name,id_coll[1]);
var joined_id_2 = String.concat(front_name,id_coll[2]);
var joined_id_3 = String.concat(front_name,id_coll[3]);
$(joined_id_0,joined_id_1,joined_id_2,joined_id_3).wrapAll('<div>');
With:
$('#'+id_coll.join(', #')).wrapAll('<div>');
And remove the line: var front_name = '#';
You have to concatenat the ids, separated by a comma, as in #id1, #id2, ....
You can do that this way:
[joined_id_0,joined_id_1,joined_id_2,joined_id_3].join(',')
The whole line:
$([joined_id_0,joined_id_1,joined_id_2,joined_id_3].join(',')).wrapAll('<div>');
If it doesn't works, check the what is returned by [joined_id_0,joined_id_1,joined_id_2,joined_id_3].join(',') (alert() it, or use console.log).

Categories