Reputation: 187
I have an AJAX that works fine. But there is a certain HTML element that I will need to completely remove before appending the AJAX response to my page.
My AJAX code looks like this:
$.ajax({
url: 'http://url-to-the-site.com',
dataType: 'json',
type: 'GET',
data: {},
success: function(data){
for( x in data ){
var articles = data[x].html;
console.log(articles);
$(".appender").before(articles);
}
},
error: function(data){
console.log(data);
}
});
So, the variable articles
has an element/tag called <footer>
.
I need to completely remove this BEFORE appending the articles
.
I tried this in my for each in my AJAX but I know this is wrong:
$(articles).find('footer').remove();
Could someone please advice on this?
Thanks in advance.
Upvotes: 0
Views: 742
Reputation: 245
I don't know much about jQuery, but I can try and solve it in pure JavaScript.
I'd try using a regular expression to remove the footer from the articles string.
Here is my attempt at it:
var example = "<article><p>Foo Bar</p><footer>Foo Bar</footer></article>";
var formatted = example.replace(/<footer>.*<\/footer>/, "");
console.log(formatted);
Output:
<article><p>Foo Bar</p></article>
Put the code above in the loop before you apped it to the DOM.
Example:
$.ajax({
url: 'http://url-to-the-site.com',
dataType: 'json',
type: 'GET',
data: {},
success: function(data){
for( x in data ){
var articles = data[x].html;
$(".appender").before(articles.replace(/<footer>.*<\/footer>/, ""));
}
},
error: function(data){
console.log(data);
}
});
[Updated]
To cater for newlines and other characters:
var formatted = example.replace(/<footer.*>(.|[\n\r])*<\/footer>/, "");
Upvotes: 1