Could be jquery used to modify html strings? - javascript

I have for example such piece of html:
var html = '<p>Title</p><b>edit me</b><i>remove me</i>';
I want to change title in it, but do not want to use regexp or string replace
functions for this, because if title would match tag name, then html could be corrupted.
I now trying to adopt jQuery for this, because it seems capable, but in reality things not so easy. Here is code:
$( $(html)[0] ).text('New title');
console.log(html); // --> prints out original html with old title
Any idea how to make this code work if it is at all possible ?

html = $('<div/>').html(html).find('p').text('New title').end().html();
http://jsfiddle.net/bEUHN/
Note: There are 3 wrapper elements in the created jQuery object using $(html), for selecting the p element you should use filter method.
$(html).filter('p').text('New title');

Related

How can I set a link for each word in a sentence?

The best way to explain my question is using the example:
https://www.priberam.pt/DLPO/casa
As you hover each word within the main content, it refers to a link for the meaning of the "hovered" word. Is it possible to configure each word to turn into a link, and refer all links to its "meaning"?
I believe that a function that turns all words into links to its "pages" would be ok.
This is what we've been trying:
var link = /wordToReplace/gi;
var urlLink = 'https://www.priberam.pt/DLPO/wordToBeReplaced';
var newLink = urlLink.replace(wordToBeReplaced, 'wordToReplace');
Thanks!
You would need to write a function that upon hover of each element with a particular class would then see the html content inside the tag and then search for the definition attaching an additional class that would display a info-layer with the content your JS would inject (the meaning of the word).
I would start writing with some pseudo-code in order to determine all the steps that your JS script would need to do to achieve this.
I would then design the HTML so that each word has a span tag with the same class as what the JS will be looking for in order to trigger this function. You can write a separate JS function to split a paragraph into an array and then append the span tag on each array value before placing the array content back into the page.
Once you have your HTML, I would write your hover function following your pseudo-code you wrote before.
Finally I would style the code that JS is injecting into the DOM with CSS to finish.
If you are fairly good with jQuery, you can have this done in a few hours, but personally I would just use vanilla JavaScript since this seems like a learning experience for you but it would take longer.
Something similar to the example below?
var textToConvert = 'Words to be converted to links';
var lookupUrl = 'http://www.merriam-webster.com/dictionary/';
var convertedText = textToConvert.replace(
/(\w+)/g,
'$1'
);
document.getElementById('output').innerHTML = convertedText;
console.log(convertedText);
<p id="output"></p>

generate HTML from a set of jQuery objects?

I am trying to modify an HTML string (things like adding class to one of its children). In my code I have to used a container as a midway to ouput $html as a string. Does jQuery provide any function to do this?
html = "<p>title</p><div><ul class='www'></ul>something</div>";
$html = $(html);
$html.filter('div').find('ul').addClass('xxx');
container = $('<div></div>');
html = container.html($html)[0].innerHTML; //output "<p>title</p><div><ul class='www xxx'></ul>something</div>"
Nope.
There is no escape to interacting with the DOM (this is creating or selecting an existing element), the best you can try is to document.write your string but you'll need to scape the HTML so it doesn't gets interpreted as HTML but text. Notice that document.write only works before the document finishes loading.
I don't know your needs but I can't think of a good use case for this, your jQuery should be better for most cases.

How to convert html correctly in javascript?

I need to convert snippets of text that contain html tags into plain text using Javascript / Node.Js.
I currently use String.Js library for that, but the problem is that when it removes the tags (using strip_tags() functions), it also removes the new line.
E.g.
<div>Some text</div><div>another text</div>
becomes
Some textanother text
Do you know how I could get rid of this problem? Maybe another library?
Thanks!
Try using Cheerio. It will expose a jQuery like interface for you on the server side. Then it's just:
var html = $(htmlstring).html();
Then just traverse the DOM for whatever elements you want and call $(element).text();
Hi this is very simple solution of your problem because I'm using reg exp and you can do what you want.
In this case we remove all tags except br tags.If you want you can remove br tag and add another tag maybe \n \t or what you want.
I hope this can help you.
Chears!!!
var html = "<div>Some text</div><div>another text</div><br />test<div>10</div>";
var removeHtmlTags = html.replace(/(<([^>!br]+)>)/ig,"");
console.log(removeHtmlTags);

Clone HTML and remove some nodes using jQuery

I'm developing a little tool for live editing using Chrome DevTools, and I have a little button "Save" which grabs the HTML and sends it to server to update the static file (.html) using Ajax. Very simple indeed.
My problem is that I need to filter the HTML code before sending it to the server, I need to remove some nodes and I'm trying to achive this using jQuery, something like this:
// I grab all the HTML code
var html = $('<div>').append($('html').clone()).html();
// Now I need to remove some nodes using jQuery
$(html).find('#some-node').remove();
// Send the filtered HTML to server
$.post('url/to/server/blahblahblah');
I already tried this Using jQuery to search a string of HTML with no success. I can't achieve to use jQuery on my cloned HTML code.
Any idea about how to do this?
The DOM is not a string of HTML. With jQuery, you do DOM manipulation, not string manipulation.
What you're doing is
cloning the document (unnecessary because you convert it to HTML anyway),
appending that cloned document to a new div for some reason
converting the content of that div to an HTML string
converting that HTML back to DOM nodes $(html) (so we're back to the first point above)
finding and removing an element in those nodes
presumably posting the html variable to the server.
Unfortunately, the html string has not changed because you manipulated DOM nodes, not the string.
Hopefully you can see above that you're doing all sorts of conversions that have little to do with what you ultimately want.
I don't know wny you'd need to do this, but all you need is to do a .clone(), then the .find().remove(), then .html()
var result = $("html").clone(false);
result.find("#some-node").remove();
var html = result.html();
Maybe like this?
var html = $('html').clone();
html.find('#some-node').remove();

jQuery append text formatting

This question is not related to coding issues but how we write our codes. For example take the append function. When we use jQuery append to insert long divs, it is easy to lose track of it's correctness. Example:
$('#someDiv').append('<div><span><div> .............. hundreds of div here ..... </div></span></div>');
Is it possible to convert this to a readable format, for example using multi-lines. I tried
$('#someDiv').append('<div>'+
+'<span>'+
+'<div> ...... and you get the point')
This doesn't seem to work. This question may be easy for some but it is not so obvious for me. Also although I minify js files at the end, it would be nice not to lose track of the elements while writing the code.
If you have to add the HTML inline style I would suggest the following format.
var html =
'<div class="somediv">\
<div class="otherdiv">\
.
..
...
</div>\
</div>';
$('#somediv').append(html);
You can do it this way -
$('#someDiv').append($('<div>').append($('<span>'))
.append($('<div>'))
.append($('<div>'))
.append($('<div>'))
.append($('<div>'))
)
You can also add css styles, add class, change html while appending these html elements (wrapped in jQuery object)
$('<div>').css('color','red')
$('<div>').addClass('someClass')
$('<div>').html("and you get the point")
My solution would be to create all these elements
div1 = $(document.createElement('div'));
div1.attr(..);
div1.css(..);
container.append(..)
This means a lot of code but you can outsource it, can easily change attributes and its good readable...

Categories