How do you document.writeln() a hyperlink? - javascript

Very simply question I can't seem to find solved here.
How can I use javascript to print a hyperlink? I'm very beginner with JavaScript and I need something like the following to work:
document.writeln("" + flaggedKCSarticles.flag_object[i].feedback_text + "");

1) Escape the internal quotes by adding a backslash:
document.writeln("<a href=\"javascript:toggleDummy1();\">" +
flaggedKCSarticles.flag_object[i].feedback_text + "</a>");
OR
2) Use single quotes:
document.writeln('<a href="javascript:toggleDummy1();">' +
flaggedKCSarticles.flag_object[i].feedback_text + "</a>");

Double quotes " are conflicting. Use a single quote in outermost, and double quotes to wrap href attribute.
So it may look like:
document.writeln('' + flaggedKCSarticles.flag_object[i].feedback_text + '')

You need to adjust quotes and double quotes so they doesn't conflict.
However, document.write and the like are very poor practice. You will learn soon enough that you need to append in a container rather than "brute print" into a document.
For example:
var a = document.createElement("a");
a.href = "javascript:toggleDummy1();";
// a more semantic way could be:
//
// a.onclick=function(event){
// toggleDummy1();
// }
//
a.innerText = flaggedKCSarticles.flag_object[i].feedback_text;
document.body.appendChild(a);

There is a problem in your markup, try this
document.writeln("" + flaggedKCSarticles.flag_object[i].feedback_text + "");
or
document.writeln("<a href='javascript:toggleDummy1();'>" + flaggedKCSarticles.flag_object[i].feedback_text + "</a>");

change your syntax like that,
document.writeln('' + flaggedKCSarticles.flag_object[i].feedback_text + '');
i hope this will work

Related

How can I use the attribute selector with a variable?

I need to use this form because it can handle spaces in my element ID.
$("div[id='content Module']").whatever();
However I need 'content Module' replaced with a variable?
I tried
$("div[id=" + my_var + "']").whatever();
but this did not work
You're missing a '
$("div[id=" + my_var + "']").whatever();
Should be
$("div[id='" + my_var + "']").whatever();
try this $("div[id='" + my_var + "']").whatever(); you forgot the open Apostrof

JavaScript appendChild text node doesn't break line

a JavaScript n00b here...
I'm generating some html code in javascript, that is going to be displayed as code via the prism HTML markup plugin. The code is dynamically added to a <pre> tag on a button click.
My javascript code is as below. It is the text in line 2, where I need a line break. I have tried /n but that doesn't work it just makes a space.
var startLabelTag = document.createTextNode("text goes here");
startLabelTag.nodeValue = "<label><strong>" + elementNameFinal + "</strong></label>LINEBREAK HERE<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('#field[" + fieldNameFinal + "]',this.value);'>";
document.getElementById("dropdown-code").appendChild(startLabelTag);
Below is the text string I'm trying to create, where a line break is made where the text LINEBREAK HERE is.
<label><strong>" + elementNameFinal + "</strong></label>LINEBREAK HERE<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('#field[" + fieldNameFinal + "]',this.value);'>
Is it something like this you are looking for?
By using String.fromCharCode(10) you can insert a line break and with the pre tag (or div having white-space: pre-wrap) the line break will be visible/shown.
var elementNameFinal = "elementname", fieldNameFinal = "fieldname";
var startLabelTag = document.createTextNode("text goes here");
startLabelTag.nodeValue = "<label><strong>" + elementNameFinal + "</strong></label>" + String.fromCharCode(10) + "<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('#field[" + fieldNameFinal + "]',this.value);'>";
document.getElementById("dropdown-code").appendChild(startLabelTag);
<pre id="dropdown-code"></pre>
Side note
You can of course use a div as well, having the CSS rule Niet the Dark Absol suggested.
<div id="dropdown-code"></div>
#dropdown-code {
white-space: pre-wrap;
}
Add white-space: pre-wrap to the container's CSS.
After all, if you type a newline in your HTML source, do you get a blank line in the result? Nope. Not without making whitespace significant through CSS.

Refering to a HTML ID with mutliple variables

So, I am trying to create a game with blocks in the level being send from the server.
I have loop cycling through the blocks each time it recieves an update from the server. It will then if the block is solid, append the block to the html document if it is not already existing.
if(blocks[blockCount].solid === true){
if($("#" + blocks[blockCount].posX.toString() + "," + blocks[blockCount].posY.toString()).length > 0){
alert("Block already exists");
}else{
$("body").append("<div style='height: " + blockSize + "px;width: " + blockSize + "px;background-color: blue;position: absolute;display: inline;margin-left: " + blocks[blockCount].posX * blockSize + "px;margin-top: " + blocks[blockCount].posY * blockSize + "px;' id='" + blocks[blockCount].posX.toString() + "," + blocks[blockCount].posY.toString() + "'> </div>");
}
}
blocks[blockCount].posX and Y should both equal to 4. But for some reason they keep being created, the if statement does for some reason not work. Can you please explain me why? or post the correct code. Thanks a lot for your help. :)
I learned here: How to check if element exists in the visible DOM?
that the jquery .length would allow me to see if the element already existed.
You can't have a , in an ID (or class for that matter) [see comment, you can, but why make life hard for yourself] - because a , is used as a separator in CSS .. i.e
#id1,div would select an element with id="id1" AND any div
you're creating elements with id's like "123,456" - which as a CSS selector would be #123,456
solution: try using _ instead of ,
also, I'm not sure if an id is allowed to begin with numbers, but don't quite me on that, if not, just prepend your id's with x or whatever
note: the HTML5 spec allows ID's to begin with numbers, however, that too does not work in CSS selectors (for CSS at least, not tested with jQuery or querySelector[All] )
you'll end up with id's like x123_456 - which is OK
Since , has a special meaning in CSS, you'd have to escape in in your selector. To write a CSS selector targeting an element with id="foo,bar", you have to write #foo\,bar. In jQuery selector allow you to do the same, but you need to remember about JS syntax and write $("#foo\\,bar") to achieve what you want (the first backslash is to escape the second one in JS string).
Also, as Jaromanda X pointed out, IDs can't start with numbers so you'll have to prepend it with a letter.
To sum up, your code may look like this:
if(blocks[blockCount].solid === true){
if($("#x" + blocks[blockCount].posX.toString() + "\\," + blocks[blockCount].posY.toString()).length > 0){
alert("Block already exists");
} else {
$("body").append("<div style='height: " + blockSize + "px;width: " + blockSize + "px;background-color: blue;position: absolute;display: inline;margin-left: " + blocks[blockCount].posX * blockSize + "px;margin-top: " + blocks[blockCount].posY * blockSize + "px;' id='x" + blocks[blockCount].posX.toString() + "," + blocks[blockCount].posY.toString() + "'> </div>");
}
}

Regex dont find if inside element?

I think I need a regular expression (javascript) that can only find a string if it is NOT inside an element. IE if I wanted to find the string "Hello" but not in the div "popup"
<div class="popup">optional content Hello world and more</div>
--No Match--
<div>This is more content Hello and welcome</div>
--Match--
Can someone point me in right direction, negative lookahead?
ok should mention how im getting it :) The find already has a reg ex to "hopefully" ignore searching inside html tags but this needs to work on top of it.
var find = "((?![^<]*>) " + data[i].GlossaryWord.trim() + " )";
var replace = " <a class=\"gobig tooltip\" " + "title=\"" + data[i].GlossaryDescription + "\">" + data[i].GlossaryWord.trim().toLowerCase() + "</a> ";
var elementContent = elementContent.replace(new RegExp(find, 'gi'), replace);
Maybe easier to use CSS selectors. Something like:
document.body.querySelectorAll('div:not(.classy)')

Add a "new line" in innerHTML

I am trying to create a table with images in first cell and information about the pic in second cell.
I need to add different information in one cell, like that:
cellTwo.innerHTML = arr_title[element] + arr_tags[element];
Is it possible to add a "new line" there?
I mean like that:
cellTwo.innerHTML = arr_title[element] + "/n" + arr_tags[element];
The simplest way is by adding a line break as html
cellTwo.innerHTML = arr_title[element] + "<br />" + arr_tags[element];
If you want your newlines to be treated literally, you could use the <pre> tag
cellTwo.innerHTML =
"<pre>" + arr_title[element] + "\n" + arr_tags[element] + "</pre>";
To round out your understanding:
Since it is html (innerHTML) it renders html and you can use any html you wish, so in this case simply add an good old fashioned <br>:
var test = document.getElementById('someElementId');
test.innerHTML = "The answer <br>to life, the universe, and everything...<br> is 42.";
If it were a string, such as in an alert box or text box etc. then /n would be correct:
alert('Never /n Forget your towel.');
Happy Coding!
- $cr1ptN!nj#
No, <br /> does not work in asp .net but you can instead write it like so
cellTwo.innerHTML = arr_title[element] + arr_tags[element]; arr_title[element] + "/n" + arr_tags[element];
Edit - alternative wrapped in code tags
cellTwo.innerHTML = arr_title[element] + arr_tags[element];
cellTwo.innerHTML += arr_title[element] + "/n" + arr_tags[element];
Semicolon ";" seems to act as line breaks
Remember the "+=" to assign multiple values to the string

Categories

Resources