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]
Related
I have a button that runs a batch file, which the code is:
<button onclick="window.open('file:///C:/Users/gthornbu/Desktop/TEST/test.bat')">Continue</button>
I can put that directly in the HTML file and it works just fine, however I am inserting this specific piece of code into the file via output.innerHTML and it's not working. I assume the "/" have to be changed, but I have also tried:
<button onclick='window.open('file:///C:\\Users\\gthornbu\\Desktop\\TEST\\test.bat')'>Continue</button>...which also does not work. Any ideas what I'm missing here?
JavaScript I am using:
function novpn() {
var output = document.getElementById("main");
var sentence = "<h3>You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.</h3></br><button onclick='window.open('file:///C:\\Users\\gthornbu\\Desktop\\TEST\\test.bat')'>Continue</button>";
output.innerHTML = sentence;
}
You have ' nested within '.
The easy way out is to use ", but escaped, as the inner quote. Then go back to the original URL (with forward slashes):
var sentence = "<h3>You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.</h3></br>" +
"<button onclick='window.open(\"file:///C:/Users/gthornbu/Desktop/TEST/test.bat\")'>Continue</button>";
You can declare strings with ", ' characters. If you have to call a function with parameter in html attribute, declaration may become a problem.
You can resolve this with escape character. \
It will escape behaving the character caused. You must add before it.
var str = "string";
var str2 = \""string\"";
str === str2 // true
In your case, you can do it like this.
output.innerHTML = '<button onclick="window.open(\'file:///C:/Users/gthornbu/Desktop/TEST/test.bat\')">Continue</button>'
Working JS Fiddle
http://jsfiddle.net/ebilgin/wLe04pwg/
Nesting html markup and javascript code in strings can become an headache to get the single and double quotes right and escaped where needed. Although it allows for some rather rapid application development if you need to maintain this later you might give this solution try.
Instead of figuring out which quote needed to go where I recreated your target html in vanilla javascript commands to create the same result by using different functions and wiring it all together.
I used the document.createElement function to create the html elements needed and the appendChild function to add them to the main element. The button get the function for opening the window attached to the onclick event.
function novpn() {
var output = document.getElementById("main");
// create the h3 elelement and its content
var h3 = document.createElement('h3');
h3.innerHTML = "You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.";
// the br
var br = document.createElement('br');
// create the button
var button = document.createElement('button');
button.innerHTML = "Continue";
// the onclick handler can now become
// a normal javascript function
button.onclick = function() {
window.open('file:///C:/Users/gthornbu/Desktop/TEST/test.bat');
};
// add all created elements to main
output.appendChild(h3);
output.appendChild(br);
output.appendChild(button);
}
// start
novpn();
<div id='main'>
<div>title</div>
</div>
I got some html code as a response from an ajax call. And I want to get the content of a specific div. Here's the html:
<html>
.
.
<div id="div-test">
.
.
</div><!--/div-test-->
.
.
</html>
Note: I use the <!--/div-test> because div#div-test contains more divs.
And that's my regex:
/<div[^.]*id=\"div\-test\"[^.]*>(.*?)<\/div><\!\-\-\/div\-test\-\->/
But it doesn't work at all. When I try to match it, all I get is a null value. So, is my regex wrong or is there anything else I need to do?
If you're looking for a non-regex approach, and you don't want to append the content on the page directly, you can create a document fragment and search through there:
var content = ""; // HTML FROM AJAX
var div = document.createElement('div');
div.innerHTML = content;
ajax_element = div.firstChild;
var test_content = ajax_element.getElementById('div-test').innerHTML;
as a regex approach, as much as I could advise against it, this might fit your needs:
var search_id = "div-test";
var r = new RegExp("<div[^>]*?id=[^\"]*?[^']*?"+search_id+"[^\"]*?[^']*?[^>]*?((?s).*)<\/div><!--\/"+search_id+"-->");
You can use the regex :
<div[^>]*?id='div-test'[^>]*?>(.*?)<\/div><!--\/div-test-->
Output
Or if the makup is with "" you can use
<div[^>]*?id=\"div-test\"[^>]*?>(.*?)<\/div><!--\/div-test-->
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);
I have different sentences which all have double quotes in them, like:
<h3 class="myClass">Sentence one "ends like this"</h3>
<h3 class="myClass">Sentence two"ends like that"</h3>
<h3 class="myClass">Sentence three "another ending"</h3>
All on a page. Basically all values are differents, and I'm trying to have a line break just before the double quote so it would be like
<h3 class="myClass">Sentence one <br/>"ends like this"</h3>
<h3 class="myClass">Sentence two <br/>"ends like that"</h3>
<h3 class="myClass">Sentence three <br/>"another ending"</h3>
I'm kind of confused on which jQuery function should be used to be honest, between split, text ? Any help would be appreciated , I need to understand how to do this... Many thanks!
You can match the <h3> elements, then pass a function to html(). That function will be called for each element, will be passed the current element's inner HTML markup, and must return the new markup.
From there, you can use replace() to insert a <br /> element before the first double quote character:
$("h3.myClass").html(function(index, currentHtml) {
return currentHtml.replace('"', '<br />"');
});
You can test this solution in this fiddle.
Make a function that takes a jQuery object, gets its html, and changes it
function addBR($el) {
Get the element's html
var originalhtml = $el.html();
Split the html by the quotation mark, and join them with a new <br />
var newhtml = originalhtml.split('"').join('<br />"');
Apply the new html
$el.html(newhtml);
And that's it.
Call it with
addBR(jQuery element);
Example: http://jsfiddle.net/XFC5u/
I would take a look at the Javascript split() method but in essence you have the right idea. You want to split based on the double quote(\") and that will return you an array of all the splits where a double quote occurs.
So something like this would happen:
var array = $(".myClass").text().split("\"");
//array = [Sentence one, ends like this, ];
(Not 100% sure if code is right so someone please check ><)
and then from there you can kind of recreate the text with the included . At least that's the process of how I would go about it.
Also just remember that the split method does remove the \" from the array (because it uses it as a limiter to split them) so make sure to readd them when you are recreating the text.
As for if Jquery as a specific way of doing this, I'm not sure. If anyone would like to improve my answer, feel free.
Take a look here to see this code working:
$(".myClass").each(function() {
var text = $(this).text();
var q = text.indexOf('"');
$(this).html(text.substr(0, q) + "<br />" + text.substr(q));
});
just with some basic javascript (inside a jQuery loop offcourse)
$(".myClass").each(function() { // for each item of myClass
var text = $(this).text(); // temp store the content
var pos = text.indexOf('"'); // find the position of the "
$(this).html(text.slice(0,pos) + '</br>' + text.slice(pos)); // slice before + <br> + slice after = new content
});
fiddle:
http://jsfiddle.net/JaPdT/
$('.myClass').each(function(){
if($(this).text().indexOf('"') >=0 ){
$(this).text( $(this).text().replace('"', '<br/>"') )
}
})
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.