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"}
Related
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);
I have a div element with lots of descendent's elements, all with ids in the form "word1", for a simple example: id="moviment1" or id="type1".
I need to get only the written part of these ids (moviment or type), in order to concatenate their names with a increment of 1 (id="moviment2" or id="type2").
$clone.find('*').each(function() {
var id = $(this).prop('id');
var num = parseInt( $(this).prop("id").match(/\d+/g), 10 ) +1;
$(this).prop('id', id+num);
});
The way it is, I always get ids like id="moviment12". I already tried:
var id = $(this).prop('id').replace(/\d+/g, '');
or
var id = $(this).prop('id').match(/\w+/);
But I always get errors like "cannot read property 'replace'/'match' of undefined". So, what am I doing wrong? Any other ideas? Thank you very much!
Ideally you should use a template. Traversing and modifying parsed elements makes your code slow and hard to maintain.
If you want to increment the number part of the IDs by 1 you can use the replace method callback function:
$clone.find('[id]').prop('id', function(_, id) {
// Assuming `id` is `test_25_segment`
return id.replace(/(\d+)/, function(num) {
// |
// --- is 25
return +num + 1;
// |
// --- parses the matching string into integer
});
});
Here is a demo using the above snippet.
Easiest way, you could just add those values as data-attr:
<div id="type1" data-id="1" data-text="type"></div>
So you can easily get them separated just using .data('id') and .data('text').
You may select the elements by this way:
var all = [].filter.call(document.querySelectorAll('[id*=type]'), function(el) {
return (/\btype\d+\b/).test(el.id);
});
and then you can change the ids using methods like replace()
Try this...
var onlyAlphabets = id.split(/(\d)/)[0];
I have a following variable
var $pk3s_c = $('<input id = query_form_tbl_info_'+query_index +'_pk3ss[] name =query_form[tbl_info]['+query_index+'][pk3ss][] type = hidden></input>');
and an array
var pk3s = opts[tbl]["cols"];
during iteration through the array, I want to append the elements of an array to $pk3s_c
$.each(pk3s, function(i,pk3){
$pk3s_c.attr('value',pk3);
})
the code above is not working, it shows me that I have appended only last element of a pk3s, and not all of them. How can I append each element of p3ks into my hidden input?
You aren't going to get an array into a string field without converting it into a string.
The JSON format is very useful for this
// convert the array to a string
var myString = JSON.stringify(myArray);
// put the string into the field as it's value
$('input').val(myString);
Javascript can interpret the resulting string and server side languages can easily convert it from a string into an array value they can understand (see for php, ruby)
Here is an example in a jsfiddle
For readability, I would pass the arguments as a parameter to the jQuery function
Would look like
var values = ['argument1', 'argument2', 'argument3'];
var query_index = 43;
var jqueryAttributes = {
id: 'query_form_tbl_info_' + query_index + '_pk3ss[]',
name: 'query_form[tbl_info][' + query_index + '][pk3ss][]',
type: 'hidden',
value: JSON.stringify(values)
// if your server don't support HTML encoding, use the one below instead
// value: "['"+values.join("','")+"']"
};
var $newElement = $('<input/>', jqueryAttributes);
alert('you element would look like : ' + $newElement[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
I have an array with divs ids (in my case its all divs ID values od parent div (#area) ):
jQuery.fn.getIdArray = function () {
var ret = [];
$('[id]', this).each(function () {
ret.push(this.id);
});
return ret;
};
var array = $("#area").getIdArray();
I need to get an array field value, something like this:
var lef = $("#array".[0]).css("left");
Taking a wild swing at it (see my comment on the question):
var array = $("#area").getIdArray();
var lef=$("#" + array[0]).css("left");
That assumes that getIdArray returns an array of strings, where each string is an id value for a DOM element, and that you want to get the left value for the first of those elements.
So for instance, if the array comes back as:
["foo", "bar", "charlie"]
then the selector created by "#" + array[0] is #foo, so you end up getting the left value for the foo element.
If you have an actual JS array within your variable array just use bracket notation to access each individual ID.
// I have the # before-hand since I'm assuming you have just the ID name
var lef = $('#' + array[0]) // this will access the 1st one in the array
I think you are looking for this :
var divYouWantToChange = $("#"+array[0]);
I try to formulate this as an answer because getIdArray is not a jquery function and we don't know what it does. If you'd like to apply a custom filter to the $("#area") collection you can do so using filter. This will return a jquery object where you can get the .css("left") from.
If you'd like to save both the id's and the left property you can do so with the following code:
var objects=[];
$("#area").filter(function(){
$this=$(this);//cache the object
objects.push({id:$this.attr("id"),
left:$this.css("left")
};
});
console.log(objects);
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)