I have a string containing html elements, now I need to select some elements and remove them from the string.
In JQuery I tried the following:
html_string = "<ul><li data-delete>A<li><li>B</li></ul>";
html_clean_string = $(html_string).remove('[data-delete]').html();
This is what I expected:
"<ul><li>B</li></ul>"
But I got the same original string. So how can I use CSS selectors to remove html elements from a string?
You can do it like this:
var html_string = "<ul><li data-delete>A</li><li>B</li></ul>";
var elems = $(html_string);
elems.find('[data-delete]').remove();
var html_clean_string = elems[0].outerHTML;
You had a couple of issues:
.remove() only operates on the elements in the jQuery object, not on child object so you have to .find() the appropriate child elements before you can remove them.
Since you want the host top level HTML too, you will need the .outerHTML.
You had mistakes in your html_string.
Working jsFiddle: http://jsfiddle.net/jfriend00/x8ra6efz/
You can also save a little jQuery with more chaining like this:
var html_string = "<ul><li data-delete>A</li><li>B</li></ul>";
var html_clean_string = $(html_string).find('[data-delete]').remove().end()[0].outerHTML;
Working jsFiddle:http://jsfiddle.net/jfriend00/wmtascxf/
Related
I'd like to use a variation of this code, but I'm having a bit of trouble concatenating the following snippet. Essentially using a for loop from a returned value.length and append the buttons, then replace data for buttons:
for(var i...){
var button = "'<button>%data%</button>'";
$(".buttons").append(button).replace("%data%", var);
};
You don't need to make the replace after you append the element. You should just set var directly on element either with text or html, depending on what var holds. Also, please notice that jQuery doesn't have a method called replace, it only has replaceWith (http://api.jquery.com/replaceWith/) and replaceAll (http://api.jquery.com/replaceAll/).
for(var i...){
var button = $("<button></button>").text(var);
$(".buttons").append(button);
};
When I do this:
var elem = $(".region_box");
text = elem.find(".my_text").html();
I can get text from the first element deep below "elem" with class "my_text" which it finds.
But there are many elements of the class "actual_text" below elem and I want to combine the text from all of them. How would I do it?
I am new to jQuery and I searched around for solution for long time, but neither of them worked for me. Perhaps I am using this each() function incorrectly. I would very much appreciate any help.
You can use the jQuery.each
var text = '';
var elms = $(".region_box .my_text").each(function () {
text = text + $(this).text(); // use .html() if you actually want the html
});
Define a variable to hold the new string, select all of the elements you wish to extract, chain that with .each() and add the contents of the text node for that element to the variable you created to hold the new string.
(Demo)
var text = "";
$(".region_box .my_text").each(function(){ text += " " + $(this).text(); });
try something using jquery .map() method like this,
text = $('.region_box').find('.my_text').map(function() {
return $(this).text();
}).get().join(',');
As the site said, "As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array."
I have an html string that I created with a template.
This string has an html table with a bunch of rows, I'd like to manipulate this string using jquery, for example to add some classes to some rows based on logic, or other manipulation and then have jquery return a string. However, it seems that jQuery only manipulates the DOM. But I don't want to post this string into the DOM yet.
var origString = "<table><tr id='bla'>...more html inside here...</tr></table>";
//Something like
var newString = $(htmlString -> '#bla').addClass('blaClass');
// this syntax is obviously wrong, but what I mean is I'm trying
// to look inside the string not the dom
Or maybe it's better to post this string into an invisible div first and then manipulate it with jquery?
Parse it to a variable, manipulate, then append:
var origString = "<table><tr id='bla'>...";
origString = $.parseHTML(origString);
$(origString).find("tr").addClass("test");
$("body").append(origString);
Concept demo: http://jsfiddle.net/6bkUv/
Yeah, you can add a class without appending it to the dom.
var origString = "<table><tr id='bla'>...more html inside here...</tr></table>",
newString = $('<div>'+origString+'</div');
newString.find('#bla').addClass('blaClass');
console.log(newString.html());
Yes, you can definitely manipulate a string with jQuery. Here is what the following code does:
Declares a div to wrap the string in
Wraps the string in the div and does the manipulation
Finally, produces the manipulated string
No interaction with the DOM whatsoever.
var htmlString = "<table><tr id='bla'>...";
var div = $('<div/>');
div.html( htmlString ).find( '#bla' ).addClass( 'class' );
var newString = div.html();
WORKING JSFIDDLE DEMO
//OUTPUT
Original: <table><tr id='bla'><td></td></tr></table>
New: <table><tbody><tr id="bla" class="class"><td></td></tr></tbody></table>
NOTE: Please note that if your table string does not have a tbody element jQuery will include it as that makes for valid table markup.
The answers were too complicated. The answer is just a dollar sign and some parentheses:
var queryObj = $(str);
So
var str = "<table><tr>...</tr></table>"
var queryObj = $(str);
queryObj.find('tr').addClass('yoyo!');
// if you use 'find' make sure your original html string is a container
// in this case it was a 'table' container
$("body").append(queryObj);
works just fine..
how do i extract all the img html tags out of the javascript variable that looks like this:
var content = '<img src="http://website.com/image.jpg"><img src="http://website.com/image2.jpg"><img src="http://website.com/image3.jpg">Other content';
And then extract each img link , probably using jQuery .each() function.
Image link extracted will be
http://website.com/image.jpg
http://website.com/image2.jpg
http://website.com/image3.jpg
How can I do this? do i need regex?
You can create a jQuery collection of html elements from a valid html string without even appending them to any document. This will work like a normal jQuery collection.
$(content).filter('img').each(function () {
console.log($(this).attr('src'));
});
EDIT: If the images will always be the children of another element in content, use .find instead of .filter. Otherwise, you have to use both simultaneously, which you can still do:
$(content).find('img').addBack().filter('img').each(function () {
For single-level DOM this will work nicely:
var links = $(content).filter('img').map(function() {
return this.src;
}).toArray();
console.log(links); //["http://website.com/image.jpg", "http://website.com/image2.jpg", "http://website.com/image3.jpg"]
Fiddle
If you have multiple levels of DOM (nested images inside other elements) change first line to:
var links = $('<div>').append(content).find('img').map(function() {
Also, if you're scraping arbitrary data, you should use $.parseHTML (jQuery 1.8+) to be safe from XSS.
Here's the complete, sturdy version:
var links = $('<div>').append($.parseHTML(content)).find('img').map(function() {
return this.src;
}).toArray();
jsBin
In the above example, I'm appending the content to a dynamically created div element so I can perform just a single find operation. The result is the same as #Explosion Pills' .find('img').addBack().filter('img') variation.
Also, obviously, if you already have the images in the page, you can use a common ancestor as the root for .find() instead of creating new DOM elements:
var links = $('#imagesParent').find('img').map(function() {
You're right, using .each() to iterate over it works fine.
var ary = [];
var content = '<img src="http://website.com/image.jpg"><img src="http://website.com/image2.jpg"><img src="http://website.com/image3.jpg">Other content';
$(content).each(function () {
ary.push($(this).attr('src'));
});
jsFiddle example
LIVE DEMO Using .map() and .get()
var srcs = $(content).map(function(){
return this.src;
}).get();
http://api.jquery.com/map/
http://api.jquery.com/get/
LIVE DEMO Using .each() and an array to store data
var srcArray = [];
$(content).each(function(){
srcArray.push(this.src);
});
http://api.jquery.com/each/
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push
My jQuery question I beleive is pretty simple, which is driving me insane that I can't get it.
I have an object with a property "content", I want to be able to take that object, manipulate the property "content" with jQuery and then overwrite the value with the new value jQuery creates.
Example:
o.content = "<div><span>hello</span></div>";
$('div', o.content).addClass('test');
At this point I want o.content to be equal to <div class='test'><span>hello</span></div>
I can not for the life of me figure out the syntax. Any help is really appreciated.
This will give you a string <div class="test"><span>hello</span></div> if this is what you want:
$(o.content).addClass('test').wrap('<div>').parent().html();
Parse the html in o.content, add the class, append the parsed html to a new <div>, and get the html of the new div:
o.content = "<div><span>hello</span></div>";
var el = $(o.content).addClass('test');
o.content = $("<div>").append(el).html();
Edit: This assumes you want o.content to still contain a string, rather than a jQuery object. In that case, it's simpler:
o.content = $(o.content).addClass('test');
from the docs of the jquery function, context must be
A DOM Element, Document, or jQuery to use as context
Your context (o.content) is a string. Also, the jQuery function is not able to select the entire context, it can only select elements in that context.
Try this instead:
// make o.content a jquery element, not a string
o.content = $("<div><span>hello</span></div>");
// select on something inside the context (inside the div), not the div itself
$('span', o.content).addClass('test');
http://jsfiddle.net/JfW4Q/
I don't think you can lookup an element from a string like that.. I would rather do it like below,
var content = "<span>hello</span>";
content = $('<div/>', {class: 'test'}).html(content)
DEMO: http://jsfiddle.net/k4e5z/
You want the following
o.content = "<div><span>hello</span></div>";
// Create a jQuery object you can call addClass on
var docFragment = $(o.content);
docFragment.addClass('test');
// Since there's no outerHTML in jQuery, append it to another node
var wrapper = $('div');
docFragment.appendTo(wrapper);
// The HTML of the wrapper is the outerHTML of docFragment
console.log(wrapper.html()); // outputs <div class='test'><span>hello</span></div>
Why not do it all in one line:
var o = {};
o.content = $( "<div></div>" ) // create element
.addClass('test') // add class
.html( '<span>hello</span>' ); // append content
Fiddle: http://jsfiddle.net/kboucher/eQmar/
o.content = $("<div><span>hello</span></div>");
o.content.addClass('test');
o.content is a jQuery object in this example, as opposed to just a string. Here's a demo on jsfiddle: http://jsfiddle.net/cvbsm/1/