jQuery: create html elements from comma separated string? - javascript

I'm trying to create HTML elements (div's) from a comma separated string using jQuery.
Lets say I have a string that looks like this:
options ="some texts, another text, some more text";
and I need to create something like this:
<div>some texts</div>
<div>another text</div>
<div>some more text</div>
I first split the comma separated string like so:
var str = options;
var temp = new Array();
temp = str.split(", ");
And then I need to create the div's after this function which I have no idea how to do this.
Could someone please advise on this?

Try this:
var options ="some texts, another text, some more text";
var temp = options.split(", "); // first split string and convert it to array
var str = '';
$.each(temp, function(i,v) { // loop through array
str += "<div>"+v+"</div>"; // create html string and store it in str variable
});
$("body").append(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

You can do something like this using jQuery
var options = "some texts, another text, some more text";
var temp = options.split(", ");
// iterate and generate array of jQuery elements
var divs = temp.map(function(txt) {
// generate div using jQuery with text content as array element
return $('<div/>', {
text: txt
})
})
// update html content, use `append()` if you want to append instead of replacing entire content
$('body').html(divs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You don't need to convert to an array- just replace the commas and associated spaces with a closing div and opening div tag and then add an opening one to start with and a closing one to end with and you have the html structure.
var options ="some texts, another text, some more text";
var temp = "<div>" + options.replace(/, /g,"</div><div>") + "</div>;
//this will give: <div>some texts</div><div>another text</div><div>some more text</div>
$("body").append(temp);

Assuming you want the text interpreted as text, not HTML, you'll want to loop over the array your code gives you and create elements individually, like this:
var options = "some texts, <another> text, some more text";
options.split(", ").forEach(function(opt) {
$("<div>").text(opt).appendTo(document.body);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Note that I changed one of your entries to demonstrate the importance of ensuring they're treated as text, not HTML.
About your code:
var str = options;
var temp = new Array();
temp = str.split(", ");
The call to new Array() is completely unnecessary there, because you're overwriting the value of your temp variable on the very next line. split returns an array, it doesn't fill in one that it magically reaches out and grabs from the left-hand side of the assignment. :-) (There's also no reason to do var str = options; Just use options directly.)

Try this:
<div id="main-div"></div>
<script type = "text/javascript">
var options ="some texts, another text, some more text";
options.split(',').forEach(function(item){
$("#main-div").append("<div>"+item+"</div>");
});
</script>

var str = options;
var temp = str.split(", ").map(function(strOption) {
return '<div>' + strOption + '</div>';
}).join('');
myHTMLElement.innerHTML = $(temp);

Related

Jquery: Replace values from one array to another

I have 2 arrays that have the exact same number of keys. I would like to loop through the first array, then search <p> tags for any matching values. Then if a match is found, I would like to replace that matching value with the corresponding value from the 2nd array.
I have this for now:
var text_original = ["original_word1", "original_word2", "original_word3"];
var text_replaced = ["replaced_word1","replaced_word2","replaced_word3"];
var z;
for (z = 0; z <= text_original.length; ++z) {
$("p").each(function(){
var text=jQuery(this).html();
$(this).html(text.replace(text_original,text_replaced));
});
}
This is the general idea, I'm getting confused how to isolate the single values from the multiple array values. Thanks in advance for help!
Use the function indexOf and check for the found text.
Use the function text rather than the function html.
var text_original = ["original_word1", "original_word2", "original_word3"];
var text_replaced = ["replaced_word1", "replaced_word2", "replaced_word3"];
$('p').each(function() {
var text = $(this).text();
var index = text_original.indexOf(text);
if (index > -1) $(this).text(text.replace(text_original[index], text_replaced[index]));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>original_word1</p>
<p>original_word2</p>
<p>Ele from SO</p>
Why $.text()?
The HTML <p> element represents a paragraph of text. Paragraphs are usually represented in visual media as blocks of text that are separated from adjacent blocks by vertical blank space and/or first-line indentation. Paragraphs are block-level elements.
The function $.text() will return the text without HTML tags.
You missing echo before json_encode().
Your json_encode() should not be wrapped into quotes.
You have to use [z] to access to an element of an array.
Code :
var text_original = <?php echo json_encode($text_original); ?>;
var text_replaced = <?php echo json_encode($text_replaced); ?>;
var z;
for (z = 0; z <= text_original.length; ++z) {
$("p").each(function(){
var text=jQuery(this).html();
$(this).html(text.replace(text_original[z],text_replaced[z]));
});
}

how to get div attributes into json

I have the following div
<div class="specialbreaek">
This div is stored in a JavaScript variable
I want to convert this into json so that i can get the class name easily
I tried JSON.parse() but still not get the required result
Any Help will be appreciated
Thanks in advance !
I see a few solutions depending on what you mean by "JavaScript variable". If the element is stored as a string, you can use a combinations of String.prototype.search() and String.prototype.substring() to extract the class. For example:
var s = '<div class="specialbreaek">';
var index = s.search(new RegExp(/class=".*"/, 'i'));
s = s.substring(index + 7);
var index = s.search(new RegExp(/"/, 'i'));
s = s.substring(0,index);
document.write(s);
If I understood you correctly, you have a div with several attributes and you want to extract them (using JS) and convert them into a JSON string.
If that's the case, you can use this to extract all attributes and then use any method you want to concatenate them into JSON
$(function() {
var mydiv = $("#mydiv");
var results = "";
// The attributes property contains all attributes of an element
$.each(mydiv.prop('attributes'), function(index, attr) {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
results += attr.name + ":" + attr.value;
results += ", ";
});
$("#res").text(results);
console.log(results);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv" class="myclass" style="mystyle">
my div text
</div>
<hr/>
<h2>results</h2>
<div id="res"></div>
To convert javascript variable into Json is JSON.stringify
Try this
$(function(){
var element = $(".specialbreaek");
var jsonstr = JSON.stringify(element);
console.log(jsonstr);
})
It will output this.
{"0":{},"length":1,"prevObject":{"0":{},"context":{},"length":1},"context":{},"selector":".specialbreaek"}

How to get the text within the a tag present in javascript variable

I want the text present in anchor tag which is present in javascript variable.
var a= 9374227
i want "9374227"
How can i get it?
Assuming a can be made as a string, use jQuery text()
var a = '9374227';
var jQueryAnchor = $(a);//convert to jquery object
var text = jQueryAnchor.text();
console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Try this out. It will give you the result as expected.
var temp = document.createElement('div');
temp.innerHTML = '9374227';
var number = temp.childNodes[0].innerHTML;
console.log(number);

How to replace text in js?

Assuming I have the following:
var s = "This is a test of the battle system."
and I had an array:
var array = [
"is <b>a test</b>",
"of the <div style=\"color:red\">battle</div> system"
]
Is there some function or way I could make it such that I can process the string s such that the output would be:
var p = "This is <b>a test</b> of the <div style=\"color:red\">battle</div> system."
Based on the arbitrary elements in the array?
Note that the array elements should be executed in sequence. So looking at the first element in array 1, find the correct place to "replace" in string "s". Then looking at array element 2, find the correct place to "replace" in string "s".
Note that the string could contain numbers, brackets, and other characters like dashes (no <> though)
Update: after Colin DeClue's remark I think you want to do something different than I originally thought.
Here is how you can accomplish that
//your array
var array = [
"is <b>a test</b>",
"of the <div style=\"color:red\">battle</div> system"
];
//create a sample span element, this is to use the built in ability to get texts for tags
var cElem = document.createElement("span");
//create a clean version of the array, without the HTML, map might need to be shimmed for older browsers with a for loop;
var cleanArray = array.map(function(elem){
cElem.innerHTML = elem;
return cElem.textContent;
});
//the string you want to replace on
var s = "This is a test of the battle system."
//for each element in the array, look for elements that are the same as in the clean array, and replace them with the HTML versions
for(var i=0;i<array.length;i++){
var idx;//an index to start from, to avoid infinite loops, see discussion with 6502 for more information
while((idx = s.indexOf(cleanArray[i],idx)) > -1){
s = s.replace(cleanArray[i],array[i]);
idx +=(array[i].length - cleanArray[i].length) +1;//update the index
}
}
//write result
document.write(s);
Working example: http://jsbin.com/opudah/9/edit
Original answer, in case this is what you meant after all
Yes. Using join
var s = array.join(" ");
Here is a working example in codepen
I suppose you've an array of original --> replacement pairs.
To extract the text from an HTML a trick that may work for you is actually creating a DOM node and then extract the text content.
Once you have the text you can use the replace method with a regular expression.
One annoying thing is that searching for an exact string is not trivial because there is no escape predefined function in Javascript:
function textOf(html) {
var n = document.createElement("div");
n.innerHTML = html;
return n.textContent;
}
var subs = ["is <b>a test</b>",
"of the <div style=\"color:red\">battle</div> system"];
var s = "This is a test of the battle system"
for (var i=0; i<subs.length; i++) {
var target = textOf(subs[i]);
var replacement = subs[i];
var re = new RegExp(target.replace(/[\\[\]{}()+*$^|]/g, "\\$&"), "g");
s = s.replace(re, replacement);
}
alert(s);

splitting an html line into separate variables with JS

In pure javascript (not using JQuery/dojo/etc), what is the best/easiest/quickest way to split a string, such as
var tempString = '<span id="35287845" class="smallIcon" title="time clock" style="color:blue;font-size:14px;" contenteditable="false">cookie</span>';
into
var id = 'id="35287845"';
var class = 'class="smallIcon"';
var title = 'title="time clock"';
var style = 'style="color:blue;font-size:14px;"';
var contenteditable = 'contenteditable="false"';
Things to note:
a "space" cannot be used as a proper delimiter, since it may appear in a value, such as title, above (time clock).
maintaining the double quotes around each variable, such as id="35287845" is important
the opening/closing span tags can be discarded, as well as the content, which in this case, is "cookie"
Here is one approach, which is to place the input string as innerhtml into a javascript created dom element and then leverage the attributes array
//Input html string
var tempString = '<span id="35287845" class="smallIcon" title="time clock" style="color:blue;font-size:14px;" contenteditable="false">cookie</span>';
//make element to contain html string
var tempDiv = document.createElement("div");
//place html string as innerhtml to temp element
tempDiv.innerHTML = tempString;
//leverage attributes array on element
var attributeArray = tempDiv.firstChild.attributes;
//log results
console.log(attributeArray);
Note that you may now do something like
var classString = attributeArray.class;
or
var titleString = attributeArray.title;
Edit
Here is a function that will do it:
function getAttributesFromString(htmlString)
{
var tempDiv = document.createElement("div");
tempDiv.innerHTML = htmlString;
return tempDiv.firstChild.attributes;
}
I think you are trying to get the properties in the span, check this response telling you how to do it.
Get all Attributes from a HTML element with Javascript/jQuery
also you could get the properties and make the string concatenating the the values with your strings.
(You can fin a explanation in pure javascript there)

Categories

Resources