How to get the variable passed through the function JavaScript/jQuery - javascript

Here is the function
function addCategory(category) {
$('#category_choice').append($('#!the variable "category" has to go in here!'));
$('#feed_submit_categories').hide();
}
The "category" variable sends the id of the element that has to be appended. How can I insert the "category" var into the function? In PHP it is much easier having $var_name tags... But here, I have no idea as to how to include it.

function addCategory(category) {
$('#category_choice').append($('#'+category));
$('#feed_submit_categories').hide();
}
Simple example of concatenation ( variables, string ):
var h = "Hello";
var w = "World!";
alert( h+w ); // HelloWorld!
alert( h+' '+w); // Hello World!
alert( h+' my dear '+w); // Hello my dear World!
jQuery selector can use string to represent literally an element ID selector:
$('#element')
that means you keep as string what you need and you concatenate a variable to it:
var elName = "element"; // string variable
$('#'+ elName) // same as: $('#element')
If you need to append every time a new fresh element do like:
$('#category_choice').append('<div id="'+category+'" />');
just make sure not to duplicate your elements ID for ID has to be unique per page element.

Use
function addCategory(category) {
$('#category_choice').append( $('#'+category) );
$('#feed_submit_categories').hide();
}

$('#category_choice').append($('#'+category));
jQuery selectors are just strings that are evaluated, you can generate a string following basic Javascript rules.
For example :
var iAmString = "#"+category;
$(iAmString) //<-- using string var as a selector

Related

How can I create a syntax like vue js in vanilla JavaScript?

<div id="">
<span>{{msg}}</span>
</div>
Let's think msg is variable of JavaScript and now I want to get the parent tag of {{msg}} and push a new value by innerHTML, here {{msg}} working as an identity.
demo JavaScript example:
<script>
var msg = "This is update data";
{{msg}}.parentElement.innerHTML=msg;
</scritp>
This is not actual JavaScript code, only for better understanding.
You can use jquery easily to find that element and then replace the text
var msg = "This is update data";
$(`span:contains(${msg})`).html("Its New");
In javascript:
var spanTags = document.getElementsByTagName("span");
var msg = "This is update data";
var found;
for (var i = 0; i < spanTags.length; i++) {
if (spanTags[i].textContent == msg) {
found = spanTags[i];
break;
}
}
Now, you have found that element in found and you can now change its text
if (found) {
found.innerHTML = "New text";
}
The simplest approach is to treat the entire document as a string and then re-parse it when you're done.
The .innerHTML property is both an HTML decompiler and compiler depending on weather you're reading or writing to it. So for example if you have a list of variables that you want to replace in your document you can do:
let vars = {
msg: msg, // pass value as variable
test_number: 10, // pass value as number
test_str: 'hello' // pass value as string
};
let htmlText = document.body.innerHTML;
// find each var (assuming the syntax is {{var_name}})
// and replace with its value:
for (let var in vars) {
let pattern = '\\{\\{\\s*' + var + '\\s*\\}\\}';
let regexp = new RegExp(pattern, 'g'); // 'g' to replace all
htmlText = htmlText.replace(regexp, vars[var]);
}
// Now re-parse the html text and redraw the entire page
document.body.innerHTML = htmlText;
This is a quick, simple but brutal way to implement the {{var}} syntax. As long as you've correctly specified/designed the syntax to make it impossible to appear in the middle of html tags (for example <span {{ msg > hello </ }} span>) then this should be OK.
There may be performance penalties redrawing the entire page but if you're not doing this all the time (animation) then you would generally not notice it. In any case, if you are worried about performance always benchmark your code.
A more subtle way to do this is to only operate on text nodes so we don't accidentally mess up real html tags. The key to doing this is to write your own recursive descent parser. All nodes have a .childNodes attribute and the DOM is strictly a tree (non-cyclic) so we can scan the entire DOM and search for the syntax.
I'm not going to write complete code for this because it can get quite involved but the basic idea is as follows:
const TEXT_NODE = 3;
let vars = {
msg: msg, // pass value as variable
test_number: 10, // pass value as number
test_str: 'hello' // pass value as string
};
function walkAndReplace (node) {
if (node.nodeType === TEXT_NODE) {
let text = node.nodeValue;
// Do what you need to do with text here.
// You can copy the RegExp logic from the example above
// for simple text replacement. If you need to generate
// new DOM elements such as a <span> or <a> then remove
// this node from its .parentNode, generate the necessary
// objects then add them back to the .parentNode
}
else {
if (node.childNodes.length) {
for (let i=0; i<node.childNodes.length; i++) {
walkAndReplace(node.childNodes[i]); // recurse
}
}
}
}
walkAndReplace(document.body);

javascript find element with string as id

I'm trying to write a function to with the element in my page with id equal to a string, and append children to that element. However I'm not so familiar with JS and don't know what's wrong with my function. Here is the function. The "set" is just an array as string set(It contains multiple names).
function printNetwork(set,id){
console.log("id is "+id);
var node=document.getElementById(id);
console.log("found"+node);
for(var s in set){
var className="leaf";
var content = document.createTextNode("<p class="+className+">"+s+"</p>");
console.log(content);
node.appendChild(content);
}
}
And then I called the function:
var ced ="${commented}";
console.log(ced);//ced is like "["Mike"]"
var cedArr = JSON.parse(ced.replace(/"/g, '"'));//parse it back to set
console.log(cedArr);
printNetwork(cedArr,"ced");
Reading the log from console it says "node" is foundnull, and "content" is "<p class=leaf>0</p>" and appendChild failed.
My question is, how can I pass the id into the function where it searches element by the argument? I'm used to the way Java works and now I'm a little confused with how JS works...
Suggestions are appreciated!!
Seems to work, i've used a different array than yours to make the example simple, but my guess is that you don't have any element with id ced in your DOM:
function printNetwork(set,id){
console.log("id is "+id);
var node=document.getElementById(id);
console.log("found"+node);
for(var s in set){
var className="leaf";
var content = document.createTextNode("<p class="+className+">"+s+"</p>");
console.log(content);
node.appendChild(content);
}
}
var ced = {"a": "a", "b": "b"};
printNetwork(ced,"ced");
And html:
<div id="ced"></div>
http://jsfiddle.net/eakvdr7L/

jQuery Object to HTML [duplicate]

How do you convert a jQuery object into a string?
I assume you're asking for the full HTML string. If that's the case, something like this will do the trick:
$('<div>').append($('#item-of-interest').clone()).html();
This is explained in more depth here, but essentially you make a new node to wrap the item of interest, do the manipulations, remove it, and grab the HTML.
If you're just after a string representation, then go with new String(obj).
Update
I wrote the original answer in 2009. As of 2014, most major browsers now support outerHTML as a native property (see, for example, Firefox and Internet Explorer), so you can do:
$('#item-of-interest').prop('outerHTML');
With jQuery 1.6, this seems to be a more elegant solution:
$('#element-of-interest').prop('outerHTML');
Just use .get(0) to grab the native element, and get its outerHTML property:
var $elem = $('Some element');
console.log("HTML is: " + $elem.get(0).outerHTML);
Can you be a little more specific? If you're trying to get the HTML inside of a tag you can do something like this:
HTML snippet:
<p><b>This is some text</b></p>
jQuery:
var txt = $('p').html(); // Value of text is <b>This is some text</b>
The best way to find out what properties and methods are available to an HTML node (object) is to do something like:
console.log($("#my-node"));
From jQuery 1.6+ you can just use outerHTML to include the HTML tags in your string output:
var node = $("#my-node").outerHTML;
jQuery is up in here, so:
jQuery.fn.goodOLauterHTML= function() {
return $('<a></a>').append( this.clone() ).html();
}
Return all that HTML stuff:
$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all
This seems to work fine for me:
$("#id")[0].outerHTML
The accepted answer doesn't cover text nodes (undefined is printed out).
This code snippet solves it:
var htmlElements = $('<p>google</p>↵↵<p>bing</p>'),
htmlString = '';
htmlElements.each(function () {
var element = $(this).get(0);
if (element.nodeType === Node.ELEMENT_NODE) {
htmlString += element.outerHTML;
}
else if (element.nodeType === Node.TEXT_NODE) {
htmlString += element.nodeValue;
}
});
alert('String html: ' + htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
No need to clone and add to the DOM to use .html(), you can do:
$('#item-of-interest').wrap('<div></div>').html()
It may be possible to use the jQuery.makeArray(obj) utility function:
var obj = $('<p />',{'class':'className'}).html('peekaboo');
var objArr = $.makeArray(obj);
var plainText = objArr[0];
If you want to stringify an HTML element in order to pass it somewhere and parse it back to an element try by creating a unique query for the element:
// 'e' is a circular object that can't be stringify
var e = document.getElementById('MyElement')
// now 'e_str' is a unique query for this element that can be stringify
var e_str = e.tagName
+ ( e.id != "" ? "#" + e.id : "")
+ ( e.className != "" ? "." + e.className.replace(' ','.') : "");
//now you can stringify your element to JSON string
var e_json = JSON.stringify({
'element': e_str
})
than
//parse it back to an object
var obj = JSON.parse( e_json )
//finally connect the 'obj.element' varible to it's element
obj.element = document.querySelector( obj.element )
//now the 'obj.element' is the actual element and you can click it for example:
obj.element.click();
new String(myobj)
If you want to serialize the whole object to string, use JSON.

javascript object reference by shortcuts

I have very very valuable , so i tried to make shortcuts like this :
LIVE example : http://jsfiddle.net/nqeUN/
var d = "document" ,
t = "getElementByTagName" ,
d = "div" ,
oc = "onclick";
d[t](d)[0].oc = function(){
alert("1");
}
but it's not working , what is the reason? i can see in Google plus api that all the objects are defined like this , as strings , how do they make it work?
There are a couple of problems you need to address
You have two values bound to d: "document" and "div".
It's getElementsByTagName
The getElementsByTagName function needs a DOM entry point not a string. Switch the first d to document
When using dot notation for .oc it will bound to the property oc in stead of the value of the variable oc. Use [] notation instead
Code:
var d = document ,
t = "getElementsByTagName" ,
div = "div" ,
oc = "onclick";
d[t](div)[0][oc] = function(){
alert("1");
}
Working Fiddle: http://jsfiddle.net/nqeUN/1/
Strings will work for properties, but not variable names. You also define d twice, and have the wrong method name. You would be able to do this:
var d = 'document', t = 'getElementsByTagName', div = 'div', oc = 'onclick';
window[d][t](div)[0][oc] = function() { ... }
But this really reduces readability and isn't necessary. You could run your code through a minimizer to get this automatically and still maintain readable dev code.
d is a string, not document.
You should write var d = document to get the actual document object.
However, you should not do this yourself; it makes utterly unreadable code.
Instead, you should develop normal, readable Javascript, then use a minifier (such as Microsoft AjaxMin or Google Closure Compiler) to automatically shrink your code as much as possible in production.
if you replace the values in your example, you'll see:
"document".getElementsByTagName("document").onclick = function() {};
1.) d should be set to the global document reference, not the string 'document'
var d = window.document;
2.) getElementsByTagName returns nodes that match the given tag name that are contained within the given DOM node, so passing 'document' as a string would look for HTML elements named 'document'. you need to find the divs, for example:
d.getElementsByTagName("div"); // All the 'div' elements in the document
3.) For method names to be used as strings, they need to be in brackets
document[ t ]; // document.t won't work, t is not a member
4.) Once you've accessed the nodes you care about, you need to loop through them to add event handlers to each element
var d = document.getElementsByTagName("div"),
i = 0,
len = d.length;
for ( ; i < len; i++ ) {
(function() {
// do something with d[i], the current element in the loop
})(i)
}
hope that helps! cheers.
Because the variable d is a string; and the String object does not have a getElementByTagName method.
Furthermore, your d variable is being redeclared as the string div; so you need to assign that to a different name:
var d = "document" ,
t = "getElementByTagName" ,
e = "div" ,
oc = "onclick";
Then, you need to access the window object, and retrieve the document attribute of it:
window[d]
to retrieve the Document element, and then retrieve the getElementsByTagName method from it (read getElements not getElement)
window[d][t]
You then invoke it and pass it the name of the element, retrieve the first value of the returned array, and assign a function to its onclick attribute:
window[d][t](e)[0][oc] = function () {
alert("1");
};
var d = "document",
t = "getElementsByTagName" ,
div = "div" ,
oc = "onclick";
window[d][t](div)[0][oc] = function(){
alert("1");
}
) document is not a string
) document['getElementByTagName'].call(this, 'div')
) . accessor changed to bracket because oc is a string not a property
) you used to var d twice
) it's getElementsByTagName, plural Elements
Full string madness http://jsfiddle.net/nqeUN/8/
"document"["gg"]()["getElementsByTagName"]("div")["0"]["onclick"] = function(){alert(1);};

How to get subset of string using Javascript/JQuery/JSON?

I want to get a subset of a string in Javascript. Currently, I only know how to store the entire string:
I have this as a JSON variable with a callback to foo:
foo({"results":[
"<div id=\"following\"><span>Obama</span></div>"
]})
And this is my callback function:
function foo(o){
var entireDiv = o.results[0];
}
How do I store just the "< a href = ... > ... < / a>
" tag as a string in Javascript?
With jQuery, you can parse in a piece of HTML as the second argument.
So, to update your foo function:
$j = jQuery.noConflict();
function foo(o)
{
var JustTheLink = $j( 'a' , o.results[0] ).parent().html();
}
Update:
With multiple links to handle, you can do this:
function foo(o)
{
$j('a',o.results[0]).each(handleSrc);
}
function handleSrc()
{
console.log(this); // tag
console.log($j(this).html()); // contents
}
You can use a regular expression to find the anchor tag:
function foo(o){
var entireDiv = o.results[0];
var link = /<a.+?\/a>/.exec(entireDiv)[0];
}
var link = entireDiv.match(/<a[^>]*>.*<\/a>/);

Categories