Getting InnerHtml from a javascript Variable - javascript

I make an ajax call from my page , and then in response I also get some html like this
<parent id="1"><child></child></parent>
what I want is to get Inner HTML from the Response object excluding <parent>
How can I do that?
Cant use document.getElementbyID on a variable.

you can create a jQuery wrapper for the variable content and then extract the inner html using .html()
var data = '<parent id="1"><child></child></parent>'
var x = $(data).html()

Pure JS if you like ->
http://jsfiddle.net/eztZm/
//get
var get_html = document.getElementById("parent").innerHTML;
console.log(get_html);
//set
document.getElementById("parent").innerHTML = "new html";
https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML

html code used:
<parent id="1"><child>candy</child></parent>
first approach:
var parent = document.getElementById("1");
var child_text = parent.firstChild.innerHTML;
to make a long story short:
document.getElementById("1").firstChild.innerHTML
will deliver "candy" (without jQuery) :)

Related

How to write out HTML from ajax call using JS

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);

JQuery - get attr/text from HTML string in a variable

I have a HTML string that I'm passing through a function and I want to be able to perform Jquery methods on that variable from inside the function - such as .attr('href') or .text(). I'm sure there is a simple solution for this and something more elegant then temporarily appending the DOM.
HTML
<div class="here"></div>
Javascript
link = 'Google';
// This works
$('.here').html(link);
works = $('.here').text();
console.log(works);
// This doesn't
not = link.text();
console.log(not);
http://jsfiddle.net/dfgYK/
You need to create a jQuery object from link in order to use jQuery methods on it. Try:
not = $(link).text();
DEMO: http://jsfiddle.net/dfgYK/1/
Depending on what you're doing with link, it might be beneficial to do this earlier in your code so that you can just use something like:
var $link = $(link);
console.log(link.text());
You can make a jQuery object that is not part of the DOM by passing a string in:
link = $('Google');
Then, jQuery methods will work on it:
var text = link.text();
Create the link with jQuery instead:
var link = $('<a />', {
href: "http://www.google.com",
text: "Google"
});
Then you can access it's properties with link.text() like you wanted.

Replace a word multiple times from ajax response object?

I have a ajax response object say 'var data;' .
It contains html content.
In it there is table with id='table123'.
I want to replace word say 'sample' with 'SAMPLE' form inside that table in variable 'data'.
I want to replace all occurrence of the word 'sample'using javascript or jquery.
You can use javascript replace mathod,
data.replace(/sample/g, "SAMPLE");
Update due to change in OP
var data = $(data);
changedHtml = data.find('#table123').html().replace(/sample/g, "SAMPLE");
data.find('#table123').html(changedHtml);
Create the table first and then replace the text.
// used "#id" for illustration purposes
$("#id").append( data );
var el = $('#table123');
var txt = el.html( el.html().replace(/sample/g, 'SAMPLE') );
Regarding the use of $(data) the jQuery docs state the following about passing a string into jQuery()
if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML.
So you might as well create the element in the first place and replace after.

Adding custom data attribute for a new node in Jquery does not work

I tried to use the method data (jQuery 1.7.1) in this code:
var q = '<div class="form-error-marker"></div>';
var t = $(q).data('message', message).insertAfter(el);
and it does not work.
Note that this works:
var t = $(q).attr('data-message', message).insertAfter(el);
Why does the first variant not work?
EDIT: insertAfter works correctly and new div is added after el (which is instance of one element which I get by getElementById() function; long story short I have a library that I extend).
When I say 'it does not work' I mean that the attribute 'data-message' is not stored.
Using data like that sets an arbitrary piece of data for this node; it doesn't add a new data- attribute. Just add the attribute with the attr function, and then access it with data
var q = $('<div class="form-error-marker"></div>').attr("data-message", message);
Now access it like this:
var message = q.data("message");
Here's a fiddle
When you use jQuery.data you don't change element attributes, instead your data saved in $.cache.
So if you want to change element attributes use jQuery.attr, when you want to save some info use jQuery.data

Is there a way to convert HTML into normal text without actually write it to a selector with Jquery?

I understand so far that in Jquery, with html() function, we can convert HTML into text, for example,
$("#myDiv").html(result);
converts "result" (which is the html code) into normal text and display it in myDiv.
Now, my question is, is there a way I can simply convert the html and put it into a variable?
for example:
var temp;
temp = html(result);
something like this, of course this does not work, but how can I put the converted into a variable without write it to the screen? Since I'm checking the converted in a loop, thought it's quite and waste of resource if keep writing it to the screen for every single loop.
Edit:
Sorry for the confusion, for example, if result is " <p>abc</p> " then $(#mydiv).html(result) makes mydiv display "abc", which "converts" html into normal text by removing the <p> tags. So how can I put "abc" into a variable without doing something like var temp=$(#mydiv).text()?
Here is no-jQuery solution:
function htmlToText(html) {
var temp = document.createElement('div');
temp.innerHTML = html;
return temp.textContent; // Or return temp.innerText if you need to return only visible text. It's slower.
}
Works great in IE ≥9.
No, the html method doesn't turn HTML code into text, it turns HTML code into DOM elements. The browser will parse the HTML code and create elements from it.
You don't have to put the HTML code into the page to have it parsed into elements, you can do that in an independent element:
var d = $('<div>').html(result);
Now you have a jQuery object that contains a div element that has the elements from the parsed HTML code as children. Or:
var d = $(result);
Now you have a jQuery object that contains the elements from the parsed HTML code.
You could simply strip all HTML tags:
var text = html.replace(/(<([^>]+)>)/g, "");
Why not use .text()
$("#myDiv").html($(result).text());
you can try:
var tmp = $("<div>").attr("style","display:none");
var html_text = tmp.html(result).text();
tmp.remove();
But the way with modifying string with regular expression is simpler, because it doesn't use DOM traversal.
You may replace html to text string with regexp like in answer of user Crozin.
P.S.
Also you may like the way when <br> is replacing with newline-symbols:
var text = html.replace(/<\s*br[^>]?>/,'\n')
.replace(/(<([^>]+)>)/g, "");
var temp = $(your_selector).html();
the variable temp is a string containing the HTML
$("#myDiv").html(result); is not formatting text into html code. You can use .html() to do a couple of things.
if you say $("#myDiv").html(); where you are not passing in parameters to the `html()' function then you are "GETTING" the html that is currently in that div element.
so you could say,
var whatsInThisDiv = $("#myDiv").html();
console.log(whatsInThisDiv); //will print whatever is nested inside of <div id="myDiv"></div>
if you pass in a parameter with your .html() call you will be setting the html to what is stored inside the variable or string you pass. For instance
var htmlToReplaceCurrent = '<div id="childOfmyDiv">Hi! Im a child.</div>';
$("#myDiv").html(htmlToReplaceCurrent);
That will leave your dom looking like this...
<div id="myDiv">
<div id="childOfmyDiv">Hi! Im a child.</div>
</div>
Easiest, safe solution - use Dom Parser
For more advanced usage - I suggest you try Dompurify
It's cross-browser (and supports Node js). only 19kb gziped
Here is a fiddle I've created that converts HTML to text
const dirty = "Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>";
const config = { ALLOWED_TAGS: [''], KEEP_CONTENT: true, USE_PROFILES: { html: true } };
// Clean HTML string and write into the div
const clean = DOMPurify.sanitize(dirty, config);
document.getElementById('sanitized').innerText = clean;
Input: Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>
Output: Hello world Many other tags are stripped
Using the dom has several disadvantages. The one not mentioned in the other answers: Media will be loaded, causing network traffic.
I recommend using a regular expression to remove the tags after replacing certain tags like br, p, ol, ul, and headers into \n newlines.

Categories