Replace HTML Using jQuery - javascript

function toText()
{
var convertHTML =$('#mainContent').html();
var ele = $(convertHTML + " > span").each(function(){
$(this).replaceWith($(this).text());
});
console.log(ele);
}
My aim is to replace the following content
<div id="mainContent">
test
<br>
1234
<br>
<span class="underline">test</span>
<br>
<span class="underline">1234</span>
</div>
And want my function to output test <br> 1234 <br> test <br> 1234
This is why i cant just use text() as it takes away the <br> aswell!

Try it like this:
function toText()
{
var ele = $("#mainContent > span").each(function(){
$(this).replaceWith($(this).text());
});
console.log(ele);
}
You where using an entire block of html as a jQuery selector :)

You were taking the html string returned from $("#mainContent").html() and trying to use it as part of the selector on the next line, when really the selector you need is "#mainContent > span".
Try this instead:
function toText()
{
$("#mainContent > span").replaceWith(function(){ return $(this).text(); });
}
You don't need an .each() loop: if you pass a function to .replaceWith() that function is called once for each element in your jQuery object and your return value is used as the replacement for the current element.
Demo: http://jsfiddle.net/7xKzP/

convertHTML from var convertHTML =$('#mainContent').html(); is not a jQuery object
You will have to write
var ele = $("#mainContent > span").each(function(){
$(this).replaceWith($(this).text());
});
Reason :
$('#mainContent').html(); will return you the string not a jQuery object for $.each to work.
var ele = $(convertHTML + " > span") would mean
var ele = $("test<br>1234<br><span class="underline">test</span><br><span class="underline">1234</span>" + " > span")

Related

replace set of strings in array

Using $('div#top_container').html(), I get the following as an example:
<div class="top" id="top_container">
<div class="example">First</div>
<div class="example">Second</div>
</div>
giving...
<div class="example">First</div>
<div class="example">Second</div>
Here, using .replace(), I want to replace <div class="example"> with *%^% (random set of characters) and remove </div>:
var content = $('div#top_container').html();
var clean_1 = content.replace('<div class="example">','*%^%'); //add $*!#$
var clean_2 = clean_1.replace('</div>',' '); //remove </div>
giving...
console.log(clean_2); --> *%^%First*%^%Second
Now, the number of example div elements can vary and I need to first find out how to target them all. Also is there a cleaner way to target both <div class="example"> and </div> at the same time?
EDIT:
I am not looking to change the html itself, but rather have the edited version as a variable that I can do stuff with (such as send it to php via ajax).
How would I do this?
Use replaceWith() method with a callback and generate prefered text string by getting text content using text() method.
$('div.example').replaceWith(function(v) {
return '%^%' + $(this).text();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="example">First</div>
<div class="example">Second</div>
</div>
UPDATE: If you don't want to update the original element then use clone() and do the remaining thinks on the cloned element.
var res = $('#parent')
// clone element
.clone()
// get element with `example` class
.find('.example')
// update content
.replaceWith(function(v) {
return '%^%' + $(this).text();
})
// back to previos selector and get html content
.end().html();
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div class="example">First</div>
<div class="example">Second</div>
</div>
Create one prototype like :
String.prototype.replaceAll = function (toReplace, replaceWith){
return this.split(toReplace).join(replaceWith);
}
and your jquery code be like :
$("div#top_container").each(function( i ) {debugger;
console.log(this.innerHTML.replaceAll('<div class="example">','*%^%').replaceAll('</div>',' ');)
});
You can use replaceWith function
$(function () {
$(".example").replaceWith(function(){
return "%^%"+$(this).text();
});
});
You can make a clone of container if you don't want to change original div.
var html="";
$(function () {
var newHtml = $("#top_container").clone();
$(newHtml).find(".example").replaceWith(function () {
html+= "%^%" + $(this).text();
});
});
console.log(html);

Remove empty p tags and convert other p tags to \n

I'm using cheerio and i have some html like this:
<p></p>
<p>test</p>
<p> </p>
<p>test</p>
<p> </p>
<p>test</p>
i'm wondering how i can format this html to something like this using javascript and cheerio.
test\ntest\ntest
so that if its an empty p tag it should be remove otherwise change it to an \n
jQuery(document).ready(function(e) {
jQuery('p').each(function() {
var $this = $(this);
if($this.html().replace(/\s| /g, '').length == 0)
$this.remove();
});
});
Select the paragraphs
Filter out the empty ones
Map the text
Turn it into an array
Join the array to map the string
.
var txt = $('p') //1
.filter(function(i, el) { //2
return $(this).text().replace(/\s+| /g,"").length;
}).map( function () { //3
return $(this).text();
})
.get() //4
.join("\n"); //5
If you have your html in html, something like this should work:
var $ = cheerio.load(html);
var result = '';
$('body').each(function() {
if ($(this).find('p').contents().length) {
result += $(this).text() + '\n';
}
});

How to properly select a div with this?

I have a list of products, each one displayed whithin a div like this :
<div data-productSheetId="n" class="productSheet"></div>
My current selector is the following :
var productSheet = $('[data-productSheetId="' + $(this).data('productSheetId') + '"]');
I'm pretty sure i'm doing it wrong, how could i select it properly ?
You can use the .filter() method:
var productSheet = $("div.productSheet").filter(function() {
return $(this).data("productsheetid") == "n";
});
Update:
Thanks to #mplungjan. The data attributes should be all lowercase. Now, when the attribute has hyphens, the camel-case equivalent can be used to read the data:
//<div data-productsheetid="n" class="productSheet"></div>
//use:
.data('productsheetid')
//<div data-product-sheet-id="n" class="productSheet"></div>
//use either:
.data('product-sheet-id')
//or:
.data('productSheetId')
You likely meant to
have an all lowercase attribute
use the data-attribute to select the productsheet by its id
like this
<div id="xxx" class="productSheet"></div>
<div id="yyy" class="productSheet"></div>
<div id="zzz" class="productSheet"></div>
<button class="btn" type="button" data-productsheetid="xxx">Select XXX</button>
$(function() {
$(".btn").on("click",function() {
// get the id to access from the button's data attribute
var id = $(this).data("productsheetid"); // for readability
var productSheet = $("#"+id);
});
});
Just lowercase your key:
productSheet = $('[data-productSheetId="' + $(this).data('productsheetid') + '"]');
The camelcase key you are using (productSheetId) is used for attributes like
<div data-product-sheet-id="n" class="productSheet"></div>
var x = 5;
var productSheet = $('div[data-productSheetId =' + x + ']');
This is going to do trick. Just change the variable x when selecting.

return the text value of tags and append a line break to each tag

So if I call this function:
$("#item").text()
on this HTML code:
<div id="item">
<pre><span class="cm-tag"><html></span></pre><pre><span class="cm-tab"> </span>asdf</pre><pre><span class="cm-tag"></html></span></pre>
</div>
it returns:
'<html> asdf</html>'
and i want it to return:
'<html>
asdf
</html>'
basically i need a new line after each <pre> tag... how would i do this?
A possible solution, get the text of each pre and join them with new lines:
var text = $("#item pre").map(function(){
return $(this).text();
}).get().join('\n');
Here is the jsfiddle: http://jsfiddle.net/uGGFe/
Another option for you:
var clone = $("#item").clone(); //create a clone we can manipulate
clone.find('pre').after('\n'); //stick new lines in after <pre> tags
alert(clone.text()); //behold the alert glory
http://jsfiddle.net/SrV9c/1/
var text = '';
$("#item pre").map(function(i, el) {
return $(el).text().replace(/\s/g, '')
}).each(function(i, val) {
if (i == 0)
text += val.concat('\n\t');
else
text += val.concat('\n');
});
​
Working sample
because jQuery search match htmlElement use regular expression, when regular expression match content first delete "\r\n", so you see the content not have "\r\n"

add what contains in element along with array

I'm trying to add the content of each span along with the value in the title attribute.
<div id="group-wrap" class="group">
<span class="lbracket" title="&f">(</span>
<span class="grouptitle" title="&f"> Group </span>
<span class="rbracket" title="&f">) </span>
<span class="username" title="&f"> Username </span>
<span class="col" title="&f">:</span>
<span class="text" title="&f"> Helo There! </span>
</div>
Here is what I have so far:
var str = [];
$('#group-wrap span').each(function(){
str.push($(this).attr('title'));
});
alert(str.join(''));
});
http://jsfiddle.net/B9QeK/3/
The output is &f&f&f&f&f (the value of each title attribute), but the expected output has the value, plus the content that is in the span. The value of the attribute should be appended before the content.
&f(&fGroup&f)&fUsername: &f text
How can I get this result?
Looks like you are looking for
str.push( this.getAttribute('title'), this.textContent || this.text );
As for performance reasons, you should not re-create a jQuery object for every single iteration. Even better, don't use jQuery at all to receive those values.
JSFiddle
And by the way, you can make usage of jQuerys .map() to do it a bit more elegant:
jQuery(function($){
var str = $('#group-wrap span').map(function(){
return this.getAttribute('title') + this.textContent || this.text;
}).get();
alert(str.join(''));
});
JSFiddle
Reference: .map()
jQuery(function($){
var str = [];
$('#group-wrap span').each(function(){
str.push($(this).attr('title') + $(this).text());
});
alert(str.join(''));
});
Working JSFiddle
text:
Description: Get the combined text contents of each element in the set of matched elements, including their descendants.
docs
Just use the text method to get the text content of each span:
var str = [];
$('#group-wrap span').each(function(){
//Push value of title attribute and text content into array:
str.push($(this).attr('title') + $(this).text());
});
alert(str.join(''));
});
Your line
str.push($(this).attr('title'));
Should look like:
str.push($(this).attr('title') + $(this).text());
Although, this is making two identical calls $(this), so you might consider caching:
var $this = $(this)
str.push($this.attr('title') + $this.text());
var str = "";
$('#group-wrap span').each(function(){
str+=$(this).attr('title')+$(this).text();
});
alert(str);
});

Categories