For example:
I have the following HTML on the DOM:
<div id="hey"><h1>Trollin</h1></div>t
If this content was on the DOM, I could simply do:
$("#hey h1").text("Hello!");
But what if the HTML was stored in a JavaScript string called "myString"? Is it possible to change the text when it is not on the DOM using jQuery or must I append it, edit it and then remove it?
If it is not possible to edit the HTML using jQuery whilst the HTML is in the variable, what is my best option?
$(myString) would convert the string of HTML (must start with a < character) to a jQuery-wrapped DOM fragment, which you can use all of jQuery's object methods on for manipulation.
.parseHTML() seems like what you're looking for. See the http://api.jquery.com/jquery.parsehtml/.
Related
I'm trying to develop a script that will take user submitted HTML, loop through it to identify matching tags, make adjustments to those matched tags, and then spit out the resulting HTML as plain text that the user can copy. The end goal here is to replace all href's in a submission and replace them with different URL's.
So for example, this:
Link A
<a data-track="false" href="http://example.com/">Link B</a>
Link C
Becomes this:
Link A
<a data-track="false" href="http://example.com/">Link B</a>
Link C
My first thought was to take the submitted HTML from the <textarea> field and put it in a variable. At this point the HTML becomes a string and I was going to loop through it with a regex to find matching tags. My issue was that I needed to find all <a> tags that did NOT include the attribute data-track="false". And as far as I can tell that's impossible with regex since each link isn't going to be on its own line.
My second thought was to loop through it using jQuery where I could use something like this:
$("a:not([data-tracking='false'])");
But I can't use jQuery like this on a string, right? It needs to be in the DOM.
I'm unsure of the best way to go about doing this. Maybe another language would prove helpful, but other than HTML and CSS, javascript and jQuery are the only ones I'm experienced with.
Any and all help would be greatly appreciated.
I think your question is similar to
Convert String to XML Document in JavaScript
The answer is that you can wrap it in a jQuery object. Then use jQuery's normal DOM manipulation methods on it.
var myhtml = $($('#main-input').val());
myhtml.find('a').each(function () {
alert($(this).text());
});
if it's a top level element you need to use filter instead of find.
You can create a jQuery object from html strings outside of the DOM and maniuplate it just the same as if it was in the DOM.
Simple example:
var html='<div><p>ABC</p></div>';
alert( $(html).find('p').text() ); // alerts "ABC"
Or
var $div= $('<div>').append(html).find('p').after('<p>DEF</p>');
var newHtml= $div.html();
Will return
<div>
<p>ABC</p>
<p>DEF</p>
</div>
Conclusion, I would loop through a jQuery object created from your html and do what you need using jQuery methods
I'm used to using jQuery's .append() method to add text or HTML onto the end of a pre-existing element. I'm currently using jQuery's .text() to escape strings that could potentially contain HTML. Unfortunately, there doesn't seem to be a jQuery method that will append the results of the .text() method to an element instead of replacing its contents.
Is there a way to append, instead of replace, this escaped text to an element? Or is there a better way to escape strings containing HTML?
Thanks.
- EDIT -
A little more context: I'm building an HTML string dynamically, and so I'll need to be able to add multiple elements with escaped content programmatically.
As I have tried many ways, I think the following method is the cleanest way to add text to whatever node you want.
no stock tag needed, only plain text, which will help to avoid potential problems
$(document.createTextNode("SomePlainText")).appendTo(p);
You could create a dummy element to hold the result of .text() which can then be appended to your destination element:
$('<div/>').text('your <span>html</span> string').appendTo(...);
You could just use
$(whatever).text($(whatever).text() + whatever_you_want_to_append);
EDIT for the fiddle in my comment, try this:
for ( /* some looping parameters */ ) {
$('<li></li>') // create an li
.text(stringWithHtml) // pass it the text, as text not html
.appendTo('#thisIsWhatINeed'); // append it where you want it
}
jsFiddle
I have a var that contains a full html page, including the head, html, body, etc. When I pass that string into the .html() function, jQuery strips out all those elements, such as body, html, head, etc, which I don't want.
My data var contains:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
</body>
</html>
Then my jQuery is:
// data is a full html document string
data = $('<div/>').html(data);
// jQuery stips my document string!
alert(data.find('head').html());
I am needing to manipulate a full html page string, so that I can return what is in the element. I would like to do this with jQuery, but it seems all of the methods, append(), prepend() and html() all try to convert the string to dom elements, which remove all the other parts of a full html page.
Is there another way that I could do this? I would be fine using another method. My final goal is to find certain elements inside my string, so I figured jQuery would be best, since I am so used to it. But, if it is going to trim and remove parts of my string, I am going to have to look for another method.
Ideas?
After a few quick tests it seems do me that this behavior isn't caused by jQuery but instead by the browser.
As you can easily verify yourself (DEMO http://jsbin.com/ocupa3)
var data = "<html><head><title>Untitled Document</title></head><body><p>test</p></body></html>";
data = $('<div/>').html(data);
alert(data.html());
yields different results in different browsers
Opera 10.10
<HEAD><TITLE>Untitled Document</TITLE></HEAD><P>test</P>
FF 3.6
<title>Untitled Document</title><p>test</p>
IE6
<P>test</P>
so this has nothing to do with jQuery, It's the browsers which strip some tags when you insert a whole html string inside a div. But you would need to step through the whole jQuery code for html() to be sure. And you would need to do that for all browsers as there are several different ways jQuery tries to do it's job.
For a solution I advise you to investigate using an iframe (possibly hidden) and to set that iframe content to the html-string you have. But be aware that fiddling with iframes and changing their content programmatically isn't an easy task either. There are also different browser related quirks and timing issues involved.
Here is a solution, which will include the body, head and other attributes:
mydoc = document.getElementById('NAME_OF_PREVIEW_FRAME').contentWindow.document; mydoc.write(HTML_CODE); mydoc.close();
Nope, the jQuery html function is just sending the string through to the element's innerHTML property, which is a function of the browser that tells it to parse the HTML into DOM elements and add them to the page.
Your browser doesn't work with a page as HTML data, it works with it as DOM and imports/exports HTML.
JavaScript has very good Regular Expression support. Depending on the complexity of your task, you may find this is the best way to process your data.
There is no need for the container div.
Have you tried this?:
var foo = $(data); // data is your full html document string
Then you can search inside of it like so:
$('.someClass', foo); // foo is the document you created earlier
Update:
As another answered mentioned, how this will act comes down to the browser.
I looked at the jQuery docs a bit and found this:
When the HTML is more complex than a
single tag without attributes, as it
is in the above example, the actual
creation of the elements is handled by
the browser's innerHTML mechanism.
Specifically, jQuery creates a new
<div> element and sets the innerHTML
property of the element to the HTML
snippet that was passed in.
So it seems that when you are using a whole html doc as a string, it's no different than setting the innerHTML property of a div you make using createElement.
Is there a way to use jQuery to search a <p> and do something to each occurrence of a string.
For example make every string "magic" in the page bold?
Is there a way to do it for a character so that every 'a' could be made bold? It appears contains just gives the element that contains the text and not the string itself.
I think i'd use a combination of JQuery and JS regexps: JQ to find the elements to process and get the contents out of each, JavaScript's replace() method to do the string manipulation, and JQ to put the modified contents back in the DOM elements.
$('p').each(function(){
$(this).html($(this).html().replace(/(bold)/,'<b>$1</b>'));
});
http://www.jquery.info/spip.php?article50
this plugin will do the bolding example. If you need it to do something else, you can modify the plugin as needed.
I'm using jquery to parse some HTML, something like:
$(html).contents().each(function(){
var element = this.tagName;
...
I can access the tagName, children, parent... using the DOM or the more friendly jQuery functions.
But at one point a need the whole HTML of the current element (not what innerHTML or .html() return) and I can't figure out a one liner to get it (I always could attach the tag and the attributes manually to the innerHTML).
For example:
Link
The innerHTML is Link but I'm looking for the whole Link
does that oneliner exists?
Looks like this guy has a pretty nifty solution using jQuery: outerHTML
just saw the anwser for this on the other thread :D
outerHTML
outerHTML 2