I have written the following code. But it is removing only not <br>
var docDesc = docDescription.replace(/( )*/g,"");
var docDesc1 = docDescription.replace(/(<br>)*/g,"");
You can achieve removing <br> with CSS alone:
#some_element br {
display: none;
}
If that doesn't fit your needs, and you want to really delete each <br>, it depends, if docDescription is really a string (then one of the above solutions should work, notably Matt Blaine's) or a DOM node. In the latter case, you have to loop through the br elements:
//jquery method:
$('br').remove();
// plain JS:
var brs = common_parent_element.getElementsByTagName('br');
while (brs.length) {
brs[0].parentNode.removeChild(brs[0]);
}
Edit: Why Matt Baline's suggestion? Because he also handles the case, where the <br> appears in an XHTML context with closing slash. However, more complete would be this:
/<br[^>]*>/
Try:
var docDesc = docDescription.replace(/[&]nbsp[;]/gi," "); // removes all occurrences of
docDesc = docDesc.replace(/[<]br[^>]*[>]/gi,""); // removes all <br>
Try this
var text = docDescription.replace(/(?: |<br>)/g,'');
Try "\n"...see if it works.
What about:
var docDesc1 = docDescription.replace(/(<br ?\/?>)*/g,"");
This will depend on the input text but I've just checked that this works:
var result = 'foo <br> bar'.replace(/(<br>)*/g, '');
alert(result);
You can do it like this:
var cell = document.getElementsByTagName('br');
var length = cell.length;
for(var i = 0; i < length; i++) {
cell[0].parentNode.removeChild(cell[0]);
}
It works like a charm. No need for jQuery.
I using simple replace to remove and br tag.
JavaScript
var str = docDescription.replace(/ /g, '').replace(/\<br\s*[\/]?>/gi, '');
jQuery
Remove br with remove() or replaceWith()
$('br').remove();
or
$('br').replaceWith(function() {
return '';
});
Related
I need to pass (using javascript) text inside span to href
<div class='tableCell'><span>information</span></div>
<div class='tableCell'><span>contact</span></div>
<div class='tableCell'><span>about</span></div>
for example when i click to about link must be example.com/tag/about/
Here is my Answer. I'm using Javascript to manipulate the DOM to add a new element with the href equal to the inner text within the span element.
I hope you find this answer helpful.
Thanks.
var spans = document.getElementsByTagName('span')
var baseUrl = 'http://example.com/tag/'
for(var i=0; i<spans.length; i++)
{
var curElement = spans[i];
var parent = curElement.parentElement;
var newAElement = document.createElement('a');
var path = baseUrl+curElement.innerHTML;
newAElement.setAttribute('href', path);
newAElement.appendChild(curElement);
parent.appendChild(newAElement)
}
DEMO
The simplest way:
$( "span" ).click(function() {
var link = 'http://yousite.com/tag/'+ $(this).text().replace(/ /, "-")+"/";
window.location.href= link.toLowerCase();
});
DEMO
http://codepen.io/tuga/pen/yNyYPM
$(".tableCell span").click(function() {
var link = $(this).text(), // will provide "about"
href = "http://example.com/tag/"+link; // append to source url
window.location.href=href; // navigate to the page
});
You can try the above code
You do not have links but span in your html. However, you can get build the href you want and assign it to an existing link:
$('div.tableCell').click(function(){
var href = 'example.com/tag/' + $(this).find('span').text();
})
Lets work with pure javascript, I know you want to use jQuery but I am really sure too many people can't do this without looking in to web with pure javascript. So here is a good way.
You can follow it from jsFiddle
var objectList = document.getElementsByClassName("tableCell");
for(var x = 0; x < objectList.length; x++){
objectList[x].addEventListener('click', function(){
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML;
});
}
Lets work on the code,
var objectList = document.getElementsByClassName("tableCell");
now we have all element with the class tableCell. This is better than $(".tableCell") in too many cases.
Now objectList[x].addEventListener('click', function(){}); using this method we added events to each object.
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML; with this line if somebody clicks to our element with class: We will change the link to his first child node's text.
I hope it is useful, try to work with pure js if you want to improve your self.
Your Method
If you always are going to have the url start with something you can do something like this. The way it is set up is...
prefix + THE SPANS TEXT + suffix
spaces in THE SPANS TEXT will be converted to -
var prefix = 'http://example.com/tag/',
suffix = '/';
$('span').click(function () {
window.location.href = prefix + $(this).text().replace(' ', '-').trim().toLowerCase() + suffix;
//An example is: "http://example.com/tag/about-us/"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tableCell'><span>Information</span></div>
<div class='tableCell'><span>Contact</span></div>
<div class='tableCell'><span>About</span></div>
You can adjust this easily so if you want it to end in .html instead of /, you can change the suffix. This method will also allow you to make the spans have capitalized words and spaces.
JSBIN
I want to "copy" a certain elements and the change some of the text inside them with a regex.
So far so good: (/w working fiddle - http://jsfiddle.net/8ohzayyt/25/)
$(document).ready(function () {
var divs = $('div');
var patt = /^\d\./;
var match = null;
for (i = 0; i < divs.length; i++) {
match = ($(divs[i]).text().match(patt));
$(divs[i]).text($(divs[i]).text().replace(match[0], "5."));
}
});
HTML
<div>1. peppers</div>
<div>2. eggs</div>
<div>3. pizza</div>
This works exactly the way I want it, but I want to add some of the content dynamically, but when I try to change the content of the copied divs, nothing happens.
Please refer to this fiddle:
http://jsfiddle.net/8ohzayyt/24/
I have put some comments, to be more clear what I want to achieve.
I thing that your problem is that you're not passing an element to your changeLabel function, but just a string.
Look at this solution: http://jsfiddle.net/8ohzayyt/26/
Here is the line I changed to make your code work:
var newContent = $("<hr/><div id='destination'>" + $("#holder").html() + "</div>");
I just wrapped your HTML in $(). this creates an element from the string.
try:
var newContent = $("<hr/><div id='destination'>" + $("#holder").html() + "</div>");
EDIT:
Brief explanation What I've done.
In order to make $(el).find('div'); work changeLabel() needs an element. Instead of passing newContent as a string doing the above will make it pass as an element which will make $(el).find('div'); work.
I'm trying to figure out a way to get the text following the element, in JavaScript, but without the classicals workarounds. My markup is:
<div class='el'>
<span class='fa fa-user'></span> Dollynho
</div>
I just want the word 'Dollynho', but without spliting the innerHTML of .el. I can do it this way:
var xs = document.getElementsByClassName('el')[0]
console.log(xs.split('>')[2].trim()) # => "Dollynho"
Can I do it in a cleaner way? (No-regex, pls)
Thanks in advance!
var xs = document.getElementsByClassName('el')[0];
xs.innerText;
in firefox you may need to user textContent
Iterate through all the childNodes and grab the content of the child nodes of type text, then remove the spureous \n
var childNodes = document.getElementsByClassName('el')[0].childNodes;
var textContent = "";
for(var i=0; i<childNodes.length; i++) {
if(childNodes[i].nodeType==3 ) {
textContent+=childNodes[i].data;
}
}
textContent= textContent.replace(/\r?\n|\r/g,"");
Fiddle: http://jsfiddle.net/53rx1t0o/11/
Use this in your script code if you want the html of your .el class is retrieved:
var x = $(".el").html();
You could get the text using jquery
$(".el").text()
Depending on your IE support needs you could use textContent https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent
var xs = document.getElementsByClassName('el')[0]
console.log(cs.textContent) # => "Dollynho"
IE has .innerText which works similarly but with some caveats (described on the textContent page above)
http://msdn.microsoft.com/en-us/library/ie/ms533899(v=vs.85).aspx
I have the next element:
<div id = "mydiv">
abc
<span>123</span>
</div>
document.getElementById('mydiv').textContent returns me: abc123
I want to get only the text of mydiv ('abc'). so I wonder if there is an option to use jquery in order to get it? maybe get all the content of an element except for span element..
and then getting his text..
p.s. I know I can wrap abc in span and then get it, but I wonder if there is another option to do it without changing my element..
DEMO JSFIDDLE
Try this ,
console.log($("#mydiv").clone() .children().remove().end().text());
You must select yours DIV by ID, then run through its "childrens" property and check their nodeType (textNodes has 3);
var div = document.getElementById("mydiv");
var result = "";
for(var i = 0; i < div.length; i++){
var node = div[i];
if( node.nodeType === 3 ){
result += node.data;
}
}
console.log(result);
Since you've included jQuery you can do this
var p = $('#mydiv').clone();
p.find('span').remove();
console.log(p.text());
DEMO
Using jQuery:
$(document).ready(function() {
alert($('#mydiv span').text());
});
If you expect to have more html elements inside your div, user regular expression to extract plain text after getting whole html content from div.
var re = /<.+>/;
var str = "abc<span>123</span>";
var newstr = str.replace(re, "");
Should give "abc"
I've been searching for a day or so how to do something with JS or jQuery and found a couple of solutions but nothing solid yet.
I want to use this:
<code class="codeIt">
<h2> This is an H2 </h2>
</code>
And I want the output to be:
<h2> This is an H2 </h2>
I know I can achieve this by doing:
<code class="codeIt">
<h2> This is an H2 </h2>
</code>
...But I would like to not do a manual search and replace on my code in those blocks and rather have it done on the fly in the browser. Is this possible?
I'm pretty noob with jQuery so I've tried .replaceWith or JavaScript's .replace but so far I've not gotten where I need to be with it. I'm either replacing the whole tag or doing something else wrong.
My question is: How would I write a simple jQuery (or regular JS) to help me replace my < and my > with HTML entities like < and > inside my <code> tags.
I appreciate any help, Thanks.
UPDATE:
I managed to get it working nice how #Prisoner explained, it's very nifty, however this in my particular case needed a little extending because I have more than one block of code with the .codeIt class, so I had to make it check each element and output... otherwise it would keep making the same output (like the first block)
Here is the fiddle
Thanks to everyone for their answers.
Assuming you just want to escape all HTML:
$(".codeIt").text($(".codeIt").html());
Plain JS for single code element
var myCode = document.getElementById('mycode');
myCode.innerHTML = myCode.innerHTML.replace(/</g,'<').replace(/>/g,'>')
Plain JS for multiple code elements
var codeEls = document.getElementsByTagName('code');
for(var i in codeEls)
{
if(parseInt(i)==i)
{
var codeEl = codeEls[i];
if(codeEl.className.match(/\bcodeIt\b/)!==null) codeEl.innerHTML = codeEl.innerHTML.replace(/</g,'<').replace(/>/g,'>')
}
}
or jQuery
$(".codeIt").each(function() {
$(this).html(
$(this).html().replace(/</g,'<').replace(/>/g,'>')
);
});
You could use the text function of jquery:
var myText = $('.codeIt').html();
var escapedText = $('.codeIt').text(myText).html();
var t = $('.codeIt').html();
$('.codeIt').text(t).html();
Look at this fiddle http://jsfiddle.net/kU8bV/1/
$('code').html($('code').html().replace(/</g, '<').replace(/>/g, '>'));
Assuming you want to code all the html in codeIt class :
<script type="text/javascript">
function htmlEncode(value){
if (value) {
return jQuery('<div />').text(value).html();
} else {
return '';
}
}
function htmlDecode(value) {
if (value) {
return $('<div />').html(value).text();
} else {
return '';
}
}
$('.codeIt').each(function() {
myEncodedString = htmlEncode($(this).html());
$(this).html(myEncodedString);
});
</script>