How to write out HTML from ajax call using JS - javascript

This might seem a little simple, but i've tried many ways & non of them are working as expected.
i have values coming in from an ajax call, & i am displaying these to a <table>.
the data will not be seen at first (css - display:none) but onclick involves a function which displays a dialog of said data.
writing out the data in these ways does not work:
var text = "Example Data<br>";
var text = document.createTextNode("Example Data" + document.createElement('br'));
var text = document.createTextNode("Example Data");
text += document.createElement('br');
The latter outputs [object Text][object HTMLBRElement]
How do i write this correctly??

You can't concatenate node objects (trying to do so with + will convert them to strings first).
Find the element you want to append the nodes you've created, and call appendChild on it repeatedly.
var text = document.createTextNode("Example Data");
someElement.appendChild(text);
someElement.appendChild(document.createElement('br'));

You need to append the line break as an HTML element "createElement" as it is an HTML element.
var text = 'test';
var newtext = document.createTextNode(text),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
p1.appendChild(document.createElement('br'));
p1.appendChild(document.createTextNode('newline displayed'));

Try
var p = document.createElement("p");
p.innerHTML = "Example Text<br>";

You can try this:
Give the table an id
Append html response to the table by using $('#tableid').html(responsedata);

Related

Selecting only Bold style data using javascript or HTML from a given text

I have a request coming in for the javascript coding and since I am very new to the javascript i am asking for some help in here.
The original text I receive in a column of csv file is in the format -
By <b>AAA</b>this is a test <b>BBB</b>this is a test2 <b>CCC</b>this is a test3
But I want to transform it using JS in the format -
AAA
BBB
CCC
Is there any way I can extract just the data that is in bold tags while deleting rest of the data, and also adding break between each finally selected text?
I would need to use this reduced data in an HTML page, so if there is a possibility of using some HTML coding, that is also quite welcome.
You can put the string inside an HTML element then use getElementsByTagName() to get the elements with the specific tag you want;
var str = 'By <b>AAA</b>this is a test <b>BBB</b>this is a test2 <b>CCC</b>this is a test3';
var div = document.createElement('div');
div.innerHTML = str;
var boldElements = div.getElementsByTagName('b');
for (i = 0; i < boldElements.length; i++) {
document.write(boldElements[i].innerHTML + '<br>\n');
}

Jquery switching elements while they are inside a variable

I'm having a little difficulty trying to switch 2 elements around with Jquery when they are inside a string variable.
eg:
var myString =
"<div class='chatMessage'>Something here
<div class='test'>My test</div>
<div class='anotherTest'> the other test</div>
Something there
</div>";
What I would like is to switch the two classes around, making "anotherTest" be infront of "test".
What I've tried so far is:
var myString =
"<div class='chatMessage'>Something here
<div class='test'>My test</div>
<div class='anotherTest'> the other test</div>
Something there
</div>";
var div1 = myString.filter('.test');
var div2 = myString.filter('.anotherTest');
var tdiv1 = div1.clone();
var tdiv2 = div2.clone();
myMessage = div1.replaceWith(tdiv2);
myMessage = div2.replaceWith(tdiv1);
However I receive the following error
t.replace is not a function
I was wondering how I would be able to achieve to switch the two divs around while still stored inside the variable before displaying it to the user?
You're making things harder on yourself by adding the constraint that this needs to be done by direct string manipulation. HTML is meant to be rendered into the DOM -- and since that's a "document object model" it stands to reason it's better-suited for modelling your document as objects.
jQuery may seem a bit old-hat, but its whole purpose is to make querying the DOM easier, so it works well here. All you need to do is parse the string, query the node you want to move, and insert it before the element you want it in front of. You can get the HTML back using $.fn.html(), or you could just leave as an element if you're going to insert it somewhere on your page.
var $el = $(myString);
$('.anotherTest', $el).insertBefore($('.test', $el));
var myMessage = $el.html();
jsfiddle here
Try this one. Just split the string by "</div>", it will make an array of splited contents, then re-add "</div>" to each splited string (this will be consumed in the process of splitting).
Then reassemble.
https://jsfiddle.net/8a4wgn7k/
var myString = "<div class='test'>My test</div><div class='anotherTest'> the other test</div>";
var res = myString.split("</div>");
res[0] +="</div>";
res[1] +="</div>";
var switchedString=res[1]+res[0]

Getting "InvalidCharacterError: String contains an invalid character" for an option in list box

I have the following line in my jsp file:
var option = document.createElement('<option value="NO">');
Not sure why this gives me InvalidCharacterError.
Any alternatives?
You can use this code to add to your tag.
var myoption = document.createElement("option");
myoption.setAttribute("value", "carvalue");
var text = document.createTextNode("maruti");
myoption.appendChild(text);
document.getElementById("mySelect").appendChild(myoption);
There was a change in DOM implementation.
Before, you could create a new element with the code inside, for instance:
BAD
var anElement = document.createElement("StackOverflow")
This implementation now, returns this ‘InvalidCharacterError’.
What you must do now is to create the element and to populate it using the innerHTML attribute or the different specific attributes for any node.
GOOD
var anElement = document.createElement("a")
anElement.innerHTML = ("StackOverflow")

Find DOM element in text content using javascript

Please push me towards a duplicate of this question if possible. I've looked everywhere but can't seem to find it.
How do I do a getElementById on text content?
var test = '<div id="thisDiv">HI</div>';
How do I select thisDiv if it's not a part of the DOM?
Create an element, set your string as its innerHTML and then search inside that ...
Something like
var test = '<div id="thisDiv">HI</div>';
var element = document.createElement('DIV');
element.innerHTML = test;
alert(element.textContent);
(changed the initial outerHTML as you can only maintain a reference to the originaly created element, and not the new one that is created by the new html)
For getting the text value inside your tags, use RegEx:
var re = new RegExp("<(.|\n)*?>", "g");
var content = test.replace(re,"");
You could create a temporary DIV and populate it with your string. Even then, your ability to access it would be limited. Add it to the DOM to access it using getElementById.
var div = document.createElement('div');
div.innerHTML = '<div id="thisDiv">HI</div>';
alert(div.firstChild);
To avoid creating that extra element, we could just add it to the body...
var test = '<div id="thisDiv">HI</div>';
document.querySelector('body').innerHTML = test;
console.log(document.getElementById('thisDiv'));
Obligatory Fiddle
Getting just the text...
console.log(document.getElementById('thisDiv').textContent); // returns HI

Add data to a string of html with JQuery

I've got a string of html that I get via $("#datadiv").html();. Within this data are several other elements, and what I would like to do is append some data to one of those elements.
e.g.
var data = $("#datadiv").html();
var somestring = "Some text"
then append somestring into the div #stringholder inside of data. Is this possible?
And before the question comes, no I can't add it to the div before doing $("#datadiv").html();.
You can do something like this:
$(data).find("#stringholder").append(somestring);
As the html method returns a string, you need to pass it into jQuery again to create a jQuery object. You can then call find to get the element you want, and append to append the other string.
jQuery is quite happy to accept a string of HTML as an argument. It's not just selector strings that are accepted. If you pass in a string of HTML, that fragment will be the context for further method calls.
I think you already know this, but note that this will not affect the HTML in the DOM. It will only affect the fragment produced by passing the string into jQuery.
Do you mean :
var data = $("#datadiv").html();
var somestring = "Some text"
var newData = data + " " + somestring;
var holderData = $("#stringholder").html();
var newestData = holderData + " " + newData;
$("#stringholder").html('');
$("#stringholder").html(newestData);
Sure. Basically you could dump the string from the current div in to a variable and then concate the additional text and put it back in the div.
var someText = $('#datadiv').html()
var someNewText = 'my new text'
var someText = someText + ' ' + someNewText
$('#datadiv').html('') //this will clear the current text but not really necessary.
$('#datadiv').html('someText')
you just need to have some event that fires to trigger everything.

Categories