Setting font style in javascript output - javascript

I am having troubles with formatting basic javascript output. Right now it is outputting in the generic times font, and I would like to change that to something like calibri.
Example:
var x = document.getElementById("textbox1").value;
document.print("<p style='font-family:calibri'>x</p>");
I'm aware that this doesn't work because it's treating it as a string literal and just outputs an x in calibri font. So how can I get it to output the variable x and keep the font formatting?
Must stay in javascript and html, can use CSS but am not very familiar at all with it.

The reason it's being treated as a string literal is because it is one.
var x = document.getElementById("textbox1").value;
document.print("<p style='font-family:calibri'>x</p>");
If you want the #textbox's value to appear you'll need this:
var x = document.getElementById("textbox1").value;
document.print("<p style='font-family:calibri'>"+x+"</p>");
Basically, that ties the three strings together, as + is an operator that not only will calculate
alert(1 + 1)
Which would come out as the integer 2
But also
'Hi.'+" I'm Jeff."
Which would come out as the string "Hi. I'm Jeff."

You don't need to use String concatenation at all to achieve this as you want to set the text contents of an element to exactly the String you've obtained
In your StyleSheet (i.e. between <style> and </style>),
.some_awesome_description {
font-family: calibri;
}
The . before the token here specifies "look for this in the class attribute"
In your JavaScript,
// get your String
var x = document.getElementById("textbox1").value;
// create a new element
var my_awesome_element = document.createElement('span');
// set it's text as the String
my_awesome_element.textContent = x;
// set it's class to be matched by the CSS
my_awesome_element.setAttribute('class', 'some_awesome_description');
// append it to the DOM tree where you want it
document.body.appendChild(my_awesome_element);
Things we used
method document.createElement to create a new element
property node.textContent to set the text of an element
method element.setAttribute to create an attribute on an element
method node.appendChild to add an element to the DOM tree
document.body, the standard way to reference the <body> of a HTML #document
<span>, a generic inline container element

Separate the x from the strings with your <p> and concatenate (+):
var x = document.getElementById("textbox1").value;
document.write("<p style='font-family:calibri'>" + x + "</p>");

Related

Can I use the % symbol in javascript or it is considered aspecial character?

I need some help.
I need to know if it is possible to use the % symbol in javascript.
I ask this question because I have an html table with the following ID= MRRMFBSY_%_CEC.
When I try to keep the TD of the second TR of this table the results is undefined, so it seems that it doesnt find the Table with this ID and also when it is defined well.
See my code below:
function getColumnsVal(id) {
var header = $("table#" + id + " thead tr:eq(1)");
var header_fields = $("td", header);
// If ID = MRRMFBSY_%_CEC when I try to do an alert of one of my TD,
// example the firstone it returns undefined
alert(header_fields[0]);
}
The question if you think that the problem is the % symbol or not, because when I have the other ID it works perfectly.
Thanks in advance
% is a reserved character, since its an operator (see).
It's not recommended, but you can use it as ID in an HTML element.
See this example:
const element = document.getElementById('MRRMFBSY_%_CEC');
console.log(element); // returns the div element
<div id="MRRMFBSY_%_CEC">
My div with a specific ID
</div>
ISSUE:
There is a problem when using certain special symbols %, ^, +, #, and so on, inside a jquery selector. They should be escaped with a backslash(\) when used because they are also used in forming the queries for the selector.
For instance '#divid' is a valid string in JavaScript but would be confusing to use in jQuery if the string was an actual id of an element. To get this element you have to use
$('#\#divid').
So, in your case to get your target element, $('#MRRMFBSY_\%_CEC') will get the element easily. However, you can either insert the escape character(\) manually or programmatically as done in this post with regular expression. Therefore, using the square brackets or the native getElementById in this answer, is just another way out of this problem.
You can definitely use % symbol in an id attribute (or in any string) as you would use the dash symbol -. However, you cannot use either of both for JavaScript variable names as they are reserved symbols.
SOLUTION:
Though this question has its own intricacies, #misorude has pointed out a solution here. So there lies your answer. use the square brackets [] or document.getElementById like this.
function getColumnsVal(id) {
// var element = $('[id="' + id + '"]'); // this line is equivalent to the next line.
var element = $(document.getElementById(id));
var header = element.find($("thead tr:eq(1)"));
var header_fields = $("td", header);
// If ID = MRRMFBSY_%_CEC when I try to do an alert of one of my TD,
// example the firstone it returns undefined
alert(header_fields[0]);
}

I am getting empty values for sports-title and third

i am new to js.
can you tell me why I am getting empty values for sports-title and third.
since we have one div with content in it.
sports-title---->{"0":{}}
third---->{}
providing my code below.
findStringInsideDiv() {
/*
var str = document.getElementsByClassName("sports-title").innerHTML;
*/
var sportsTitle = document.getElementsByClassName("sports-title");
var third = sportsTitle[0];
var thirdHTML = third.innerHTML
//str = str.split(" ")[4];
console.log("sports-title---->" + JSON.stringify(sportsTitle));
console.log("third---->" + JSON.stringify(third));
console.log("thirdHTML---->" + JSON.stringify(thirdHTML));
if ( thirdHTML === " basketball football swimming " ) {
console.log("matching basketball---->");
var menu = document.querySelector('.sports');
menu.classList.add('sports-with-basketball');
// how to add this class name directly to the first div after body.
// but we are not rendering that div in accordion
//is it possible
}
else{
console.log("not matching");
}
}
When you call an object in the Document Object Model (DOM) using any of the GetElement selectors, it returns an object that can be considered that HTML element. This object includes much more than just the text included in the HTML element. In order to access the text of that element, you want to use the .textContent property.
In addition, an HTML class can potentially be assigned to several elements and therefore GetElementsByClassName returns an array so you would have to do the following, for example:
console.log("sports-title---->" + JSON.stringify(sportsTitle[0].textContent));
You can find a brief introduction to the DOM on the W3Schools Website. https://www.w3schools.com/js/js_htmldom.asp If you follow along it gives an overview of different aspects of the DOM including elements.
Maybe this would be helpful
As you see sportsTitle[0].textContent returns full heading and 0 is the index thus you get "0" when you stringify (serialize) sportsTitle. Why 0? Because you have one <h1> element . See this fiddle http://jsfiddle.net/cqj6g7f0/3/
I added second h1 and see the console.log and you get two indexes 0 and 1
if you want to get a word from element so get substring use substr() method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
One way is to change <h1> class attr to id and do sportsTitle.textContent;
and use substr() on this string
or
2nd way is to remain class attr and do sportsTitle[0].textContent;
and substr() on this string
The 2nd is the better way

Find all the links and replace them with their href value

I think I have a string like:
href text, text, test
And I need to output
site/project/109# text, text, test
I can find all links
var txt = msg.match(/\<a\shref=\"(.*)\"\s(.*)[\<\/a\>]/gmi);
And in loop make replace. But I would like to shorten the code, do everything through single replace, like this :
var txt = msg.replace(/\<a\shref=\"(.*)\"\s(.*)[\<\/a\>]/gmi, $1);
But in this case I get: [object HTMLHeadElement]
Never use regex to parse HTML, it's better to generate an element with the content and do the rest on the element.
var str = 'href text, text, test';
// create an element
var temp = document.createElement('div');
// set the content with the string
temp.innerHTML = str;
// get all `a` tags and convert into array
// for older browser use `[].slice.call()
// for converting into array
Array.from(temp.querySelectorAll('a')).forEach(function(ele) {
// create a text node with the attribute value
var text = document.createTextNode(ele.getAttribute('href'));
// replace a tag wit the text node
ele.replaceWith(text);
});
// get the updated html content
console.log(temp.innerHTML)
Why not regex ? : RegEx match open tags except XHTML self-contained tags
UPDATE : The msg variable is an element object, a not string that's why it's getting converted to [object HTMLHeadElement](HTMLHeadElement refers to the HEAD tag, I think something wrong with your core check that also). So do the same as above where replace temp with the msg. In case you want to keep the original element content then generate temp element as above and set content as temp.innerHTML = msg.innerHTML .
If you're using jQuery (which is great and does all things) then you can get the href quite easily:
var string = 'href text, text, test';
var href = $(string).attr('href');
which means that setting the text of the anchor tag is trivial:
$(string).text($(string).href));

Creating an image element with src containing certain query string parameters

I would like to create an HTML image element like this one:
<img src="www.example.com?param1=aid&param2=sid&param3=user&param4=now" />
I tried doing this:
var now = new Date().getTime();
var aid = 123456;
var sid = 78910;
var user = "abcd";
How can I create the element from this data?
You create an img element (not "tag") using document.createElement('img').
You set its src, a string, using the src reflected property of that element. To create that string, for now, you'd use string concatenation (+). See below for an ES6 note, however.
So:
var img = document.createElement('img');
img.src = "www.example.com?param1=" + aid +
"&param2=" + sid +
"&param3 = " + encodeURIComponent(user) +
"&param4=" + now;
Then you'd want to append that to the DOM somewhere.
Note the encodeURIComponent on the non-numeric one. Both the names and values in a query string must be URI-encoded. But I haven't bothered on param1, param2, etc. because I know that the URI-encoded version of them is...exactly the same. Similarly I know that the URI-encoded version of a number is just the number. But I see user is a text value, and I assume it isn't always "abcd", so to guard against issues I've URI-encoded it.
Re your comment:
And presumably if I'd like to add attributes to the img element it'd be like img.height=1 and img.width=1?
The specification lists the properties of img elements. Yes, both height and width are there and setting them has the same effect as using the height and width attributes, although you might want to use a stylesheet instead.
Not all attributes have reflected properties. For those that don't, you'd use setAttribute("name", value) (the value will be converted to a string if it isn't already one).
As of the next version of JavaScript, ECMAScript6 (ES6), you'd be able to use a template string for src instead:
var img = document.createElement('img');
img.src = `www.example.com?param1=${aid}&param2=${sid}&param3=${encodeURIComponent(user)}&param4=${now}`;
Strings in JS can be chained together with the + operator. Number values will be coerced to strings (although that sometimes won't work as expected).

How to insert HTML entities with createTextNode?

If I want to add an ascii symbol form js to a node somewhere?
Tried as a TextNode, but it didn't parse it as a code:
var dropdownTriggerText = document.createTextNode('blabla ∧');
You can't create nodes with HTML entities. Your alternatives would be to use unicode values
var dropdownTriggerText = document.createTextNode('blabla \u0026');
or set innerHTML of the element. You can of course directly input &...
createTextNode is supposed to take any text input and insert it into the DOM exactly like it is. This makes it impossible to insert for example HTML elements, and HTML entities. It’s actually a feature, so you don’t need to escape these first. Instead you just operate on the DOM to insert text nodes.
So, you can actually just use the & symbol directly:
var dropdownTriggerText = document.createTextNode('blabla &');
I couldn't find an automated way to do this. So I made a function.
// render HTML as text for inserting into text nodes
function renderHTML(txt) {
var tmpDiv = document.createElement("div"); tmpDiv.innerHTML = txt;
return tmpDiv.innerText || tmpDiv.textContent || txt;
}

Categories

Resources