JQUERY FIND:FIRST not finding the first Paragraph? - javascript

Goal, is to extract the content for the CKEDITOR Text Editor, and then only obtain the FIRST paragraph. For some reason the bellow isn't working... Ideas?
Given the following JavaScript:
var newTitle = CKEDITOR.instances.meeting_notes.getData();
newTitle = $(newTitle).find("p:first").text();

It doesn't work because find() searches the descendants and your paragraph must be at the top level of the HTML you're searching.
For example:
alert($("<p id='one'>one</p><p id='two'>two</p>").find("p:first").attr("id"));
returns "undefined" whereas:
alert($("<p id='one'>one</p><p id='two'>two</p>").filter("p:first").attr("id"));
will output "one".
So you could use filter() if you know it's at the top level (possibly falling back to find()). Alternatively you could wrap the whole lot up in a dummy element:
alert($("<div>" + html + "</div>").find("p:first").text());
Edit: My advice? Use:
newtitle = $(newtitle).filter("p:first").text();

I am not sure if works for you, but just try putting a space before :first,
for some reasons i can't explain this works as far my experience is concerned:
The new selector for find would now be, find("p: first")
var newTitle = CKEDITOR.instances.meeting_notes.getData();
newTitle = $(newTitle).find("p :first").text();
BTW can you post some sample values of the newTitle, just curious of what it looks like!

This is completely untested, but assuming that what getData returns is a string of HTML, try this:
newTitle=$("<div>").html(newTitle).find("p:first").text();

Related

Can't use document.getElementById().innerHTML to rewrite the original html

I am tring to add some content after the original content, but the new content will cover the original content everytime...What wrong in this case? (Sorry for my terrible english...)
var originaltext = document.getElementById("id").innerHTML;
document.getElementById("id").innerHTML = originaltext + "newtext";
One more thing,I tried to use alert to show the "originalltext", but it have nothing to show.
alert(originaltext);
your code looks ok to me. I made a jsfiddle for you just to see that it works http://jsfiddle.net/3mqsLweo/
var myElement = document.getElementById('test');
var originalText = myElement.innerHTML.toString();
myElement.innerHTML = originalText+" new text";
check that you only have one element with the id "cartzone"
A simple and fast way to do this is to concatenate the old value with the new.
document.getElementById('myid').innerHTML += " my new text here"
this problem usually occurs when the rest of your code is poorly written and contains errors or when the same ID is used several times.
I had the same problems in the past.
you have tow options:
check the rest of your code (validate)
use jQuery - I don't know how, but it works every time.

How to find and replace text in between two tags in HTML or XML document using jQuery?

I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;

jQuery how to insert <br/> tag after every Semicolon

I am dumping some CSS into a div and I am looking to format it so it is more legible. Basically what I want to do is insert a break tag after every semicolon. I have searched around for a while but can't seem to find something that quite fits what I am trying to do.
I have something like this...
HTML
<div class='test'>
color:red;background-color:black;
</div>​
jQuery
var test = $('.test').text();
var result = test.match(/;/g);
alert(result);​
And I have tried..
var test = $('.test').text();
var result = test.match(/;/g);
result.each(function(){
$('<br/>').insertAfter(';');
});
alert(result);​
Also I have started a fiddle here.. Which basically just returns the matched character...
http://jsfiddle.net/krishollenbeck/zW3mj/9/
That is the only part I have been able to get to work so far.
I feel like I am sort of heading down the right path with this but I know it isn't right because it errors out. I am thinking there is a way to insert a break tag after each matched element, but I am not really sure how to get there. Any help is much appreciated. Thanks...
try it like this
var test = $('.test').text();
var result = test.replace(/\;/g,';<br/>');
$('.test').html(result);​
http://jsfiddle.net/Sg5BB/
You can use a normal javascript .replace() method this way:
​$(document)​.ready(function(){
$(".test").html($(".test").html().replace(/;/g, ";<br />"));
});​
Fiddle: http://jsfiddle.net/SPBTp/4/
Use This CODE
var test = $('.test').text();
var result = test.split(';').join(';<br />')
http://jsfiddle.net/FmBpF/
You can't use jQuery selectors on text, it only works on elements.
Get the text, just replace each ; with ;<br/>, and put it back.
$('.test').html($('.test').text().replace(/;/g, ';<br/>'));
Try something like this :
var test = $('.test').text();
var result = test.replace(/;/g,";");
$('.test').html(result);
​
That should work if you stick it into your jfiddle.

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.

JS tiny text replace problem

Under normal circumstances I would simply look this up, but I don't have my JS reference so...
I have this code:
var text = document.createTextNode(alt);
var empty = document.createTextNode("");
desc.appendChild(empty);
desc.appendChild(text);
I need to alter the appendChild to something that will replace the current child value rather than add to it. I've googled for this and come up short for some reason.
Try this:
desc.replaceChild(text, desc.firstChild);
desc.innerHTML = 'some text'; - simplest way i think
Um, how about replaceChild?
desc.replaceChild(text,empty);
This replaces the empty child node with the text child node.

Categories