Get HTML without sub-children [duplicate] - javascript

This question already has answers here:
getting the first line of text in an element jquery
(5 answers)
Closed 8 years ago.
So, I have a piece of HTML code that looks something like this:
<span class="name">SOMEUSERNAME<span class="meta">20 friends</span></span>
With a simple $(".name") I can easily the insides, but is there a way to get just the username without the meta data? I know I could use RegEx, but I'd rather know if it can be done with jQuery selectors directly, since I'm still somewhat new to that thing.

Seems like something that would be easier without jQuery
document.querySelectorAll('.name')[0].firstChild.nodeValue
FIDDLE
for more elements you can do
var users = Array.prototype.slice.call(document.querySelectorAll('.name')).map(function(el) {
return el.firstChild.nodeValue;
});
FIDDLE
or for older browsers
var elems = document.querySelectorAll('.name');
users = [];
for (var i=elems.length; i--;) {
users.push(elems[i].firstChild.nodeValue);
}
FIDDLE
or more jQuery'ish
var users = $.map($('.name'), function(el) {
return el.firstChild.nodeValue;
});
FIDDLE

Try this:
var name = $('#name').clone();
name.find('.meta').remove();
console.log(name);
Hope this helps.

Try this, if you just want the username (without the 20 friends stuff)
$(".name").clone().children().remove().end().text();
http://jsfiddle.net/9GEfY/

.contents() will return all children, including text nodes. You can do something like this:
http://jsfiddle.net/MnCDb/
$(".name").contents().get(0).textContent;

Why don't you try like this?
<span class="name" id="name">SOMEUSERNAME
<span class="meta" id="meta">20 friends</span>
</span>
<button onClick="foo()">click me </button>
<div id='result'></div>
<script>
function foo(){
var names=document.getElementById('name').innerHtml;
document.getElementById('result').innerHtml=names;
}
</script>

$('span').filter(function(){return this.className=='name'}).get(0).firstChild;
jsFiddle example

Not sure this is the most efficient approach, but this should work:
$('.name').clone().children().remove().end().text();
Edit: here's a more efficient solution:
var text = $.map($('.name').contents(), function(node) {
return node.nodeType === 3 ? node.nodeValue : '';
}).join('');
Edit: just for fun, here's a potentially "more idiomatic" jQuery approach:
var text = $($('.name').contents()).filter(function() {
return this.nodeType === 3;
}).map(function() {
return this.nodeValue;
}).get().join('')

Related

Jquery to change outerhtml [duplicate]

This question already has answers here:
Can I change an HTML element's type?
(9 answers)
Closed 4 years ago.
I want to know how can I change a tag with pure javascript like that
<span>some text</span>
I want to change it to that
<div>some text</div>
I have no idea how to do it.
You can't change the type of an element like that, instead you have to create a new element and move the contents into it. Example:
var e = document.getElementsByTagName('span')[0];
var d = document.createElement('div');
d.innerHTML = e.innerHTML;
e.parentNode.replaceChild(d, e);
Demo: http://jsfiddle.net/Guffa/bhnWR/
Just written a jQuery plugin for this.
(function( $ ) {
$.fn.replaceTag = function(newTag) {
var originalElement = this[0]
, originalTag = originalElement.tagName
, startRX = new RegExp('^<'+originalTag, 'i')
, endRX = new RegExp(originalTag+'>$', 'i')
, startSubst = '<'+newTag
, endSubst = newTag+'>'
, newHTML = originalElement.outerHTML
.replace(startRX, startSubst)
.replace(endRX, endSubst);
this.replaceWith(newHTML);
};
})(jQuery);
Usage:
$('div#toChange').replaceTag('span')
The biggest advantage of this method is that id preserves all the attributes of the original element.
If jquery is acceptable use replaceWith.
$('span').each(function() {
$(this).replaceWith($('<div>' + this.innerHTML + '</div>'));
});
Here is a JSFIDDLE working DEMO
If using jquery
Var spantxt = $('span').text();
$('body').append('<div>'+spantext+'</div');
Note this would only work if there was only one span, use an id selector otherwise
You can't do it.
What you want to do is to take content of your span,
then delete it and create new div and fill it with previous content.
Assumption: The span you want to replace is wrapped in a div with id "foo"
In pure javascript you could do something like:
var original_html = document.getElementById('foo').innerHTML;
original_html = original_html.replace("<span>", "<div>");
original_html = original_html.replace(new RegExp("</span>"+$), "</div">)
document.getElementById('foo').innerHTML=original_html;
If however you can not necessarily expect the span to be tightly wrapped by an element you can consistently get (by id or otherwise), the javascript becomes fairly complex. In either case, the real answer here is: use jQuery.

Remove one of the same phrases [duplicate]

what's the best way to remove the grapes duplicate from this? there are tons of ways of removing duplicates from simple arrays, but this would be an array with html elements
<div class="fruit">
grapes
</div>
<div class="fruit">
bananas
</div>
<div class="fruit">
grapes
</div>
I've tried using something like
$('.fruit').each(function () {
$('.fruit:has("' + $(this).text() + '"):gt(0)').remove();
});
Try
var obj = {};
$('.fruit').each(function(){
var text = $.trim($(this).text());
if(obj[text]){
$(this).remove();
} else {
obj[text] = true;
}
})
Demo: Fiddle
:has expects an element selector while :contains takes a string
see http://api.jquery.com/contains-selector/
so this should do the trick:
$('.fruit').each(function () {
$('.fruit:contains("' + $(this).text() + '"):gt(0)').remove();
});
fiddle: http://jsfiddle.net/kam7E/
http://jsfiddle.net/S3wXM/1/
Assuming that you wish to remove only one of the duplicates.
Using contains, like the answer above but implementation is slightly different.
$($("div:contains('grapes')")[0]).remove();
http://api.jquery.com/jQuery.unique/ - This also might be of use to you.
var uniqueFruits = [];
$(".fruit").each(function(i,e){
var thisFruit = $.trim($(e).text());
if(uniqueFruits.indexOf(thisFruit) == -1)
uniqueFruits.push(thisFruit);
else
$(e).remove();
});
http://jsfiddle.net/a7E9e/
jsFiddle here: http://jsfiddle.net/THEtheChad/UKRwf/
var found = {};
var $unique_fruits = $('.fruit').filter(function(){
var data = this.innerHTML.trim();
if(!found.hasOwnProperty(data)) return found[data] = true;
});
Here is the working fiddle for this:-
http://jsfiddle.net/HwUUs/1/
$( "div:contains('grapes')" ).remove();

How to replace < and > with < and > with jQuery or JS

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>

jQuery javascript way of checking if some html exist on page

Before appending more code, I want to make sure:
<a href='index.php?option=com_content&view=article&id=36'>Hello</a>
isn't already on the html page inside the div where id='faqs'
<div id='faqs'>
<a href='index.php?option=com_content&view=article&id=36'>Hello</a>
</div>
What is the best way of doing this with jquery or javascript?
Thanks
The easiest way would be to use jQuery to select the element, and check the length property of the resulting object:
var anchor = $('#faqs a[href="index.php?option=com_content&view=article&id=36"]')
if(anchor.length == 0) {
// element isn't on the page
}
You could search using indexOf
var inBlock = $('#faqs').html();
if (inBlock.indexOf("<a href='index.php?option=com_content&view=article&id=36'>Hello</a>") == -1) {
$('#faqs').append ("<a href='index.php?option=com_content&view=article&id=36'>Hello</a>");
}
if (!$('a[href$="view=article&id=36"]', '#faqs').length) {
//does'nt exist
}
If the goal is to end up with the a tag as a child in the div tag, and thats it, then don't bother checking, just re add it, like this:
$('#faqs').html('');
$('<a />')
.attr('href', 'index.php?option=com_content&view=article&id=36')
.html('hello')
.appendTo($('#faqs'))​;​
However, if you genuinely need to check if it exists, then you can do something like this:
var exists = $('#faqs a[href="index.php?option=com_content&view=article&id=36"]').length > 0;
UPDATE
Finding the string in the html can be done as follows, but this is not a recommended solution. You may run into issues with different browsers encoding html in different ways etc (tested in chrome):
var stringToFind = 'Hello';
// need to replace the & ...
stringToFind = stringToFind.replace(/&/g, '&');
var exists = $('#faqs').html().indexOf(stringToFind) > -1;
if (exists) {
// do something
} else {
// do something else
}
Here's a working example -> http://jsfiddle.net/Uzef8/2/

How to get a webpage as plain text without any html using javascript? [duplicate]

This question already has answers here:
Strip HTML from Text JavaScript
(44 answers)
Closed 9 years ago.
i am trying to find a way using javascript or jquery to write a function which remove all the html tags from a page and just give me the plain text of this page.
How this can be done? any ideas?
IE & WebKit
document.body.innerText
Others:
document.body.textContent
(as suggested by Amr ElGarhy)
Most js frameworks implement a crossbrowser way to do this. This is usually implemented somewhat like this:
text = document.body.textContent || document.body.innerText;
It seems that WebKit keeps some formatting with textContent whereas strips everything with innerText.
It depends on how much formatting you want to keep. But with jQuery you can do it like this:
jQuery(document.body).text();
The only trouble with textContent or innerText is that they can jam the text from adjacent nodes together,
without any white space between them.
If that matters, you can curse through the body or other container and return the text in an array,
and join them with spaces or newlines.
document.deepText= function(hoo){
var A= [], tem, tx;
if(hoo){
hoo= hoo.firstChild;
while(hoo!= null){
if(hoo.nodeType== 3){
tx= hoo.data || '';
if(/\S/.test(tx)) A[A.length]= tx;
}
else A= A.concat(document.deepText(hoo));
hoo= hoo.nextSibling;
}
}
return A;
}
alert(document.deepText(document.body).join(' '))
// return document.deepText(document.body).join('\n')
I had to convert rich text in an HTML email to plain text. The following worked for me in IE (obj is a jQuery object):
function getTextFromHTML(obj) {
var ni = document.createNodeIterator(obj[0], NodeFilter.SHOW_TEXT, null, false);
var nodeLine = ni.nextNode(); // go to first node of our NodeIterator
var plainText = "";
while (nodeLine) {
plainText += nodeLine.nodeValue + "\n";
nodeLine = ni.nextNode();
}
return plainText;
}
Use htmlClean.
I would use:
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"></script>
<script type="text/javascript">
jQuery.fn.stripTags = function() { return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') ); };
jQuery('head').stripTags();
$(document).ready(function() {
$("img").each(function() {
jQuery(this).remove();
});
});
</script>
This will not release any styles, but will strip all tags out.
Is that what you wanted?
[EDIT] now edited to include removal of image tags[/EDIT]

Categories

Resources