Check for existence any string inside html element with jQuery - javascript

I'm aware you can do something like this:
$('.document-content p:has(br)').next('p').addClass("newClass")
to check whether a p tag has a br tag inside:
<p>
<br>
</p>
How to check if there's also for the existence of ANY string inside?
<p>
"Some text"
<br>
</p>
(The reason is, I want to remove all br inside the p tags that have a string inside.)

You can use the :contains selector:
$('.document-content contains("some text")').next('p').addClass("newClass")
If the string to find is stored in a variable you would need to concatenate it in the selector:
var searchString = 'some text';
$('.document-content contains("' + searchString + '")').next('p').addClass("newClass")
The reason is, I want to remove all br inside the p tags that have a string inside.
In this case you can get the text() of the element and overwrite the html() with it:
$('.document-content').html(function() {
return $(this).text();
});
Or
$('.document-content').html($('.document-content').text());
Both the above will work, the latter is shorter but (IMO) uglier and makes another DOM request.
Example fiddle

You can do something like thi https://jsfiddle.net/joL9xh2r/
$('p').each(function(i,ele){
if($(ele).text().replace(/\s/g, '').length>0)
{
alert($(ele).attr('id')+' has string');
}
})
Here are two paragraphs , one with string inside, and one without text, you can check if the paragraph contains a string using text(), Now you can do whatever you want within the if condition, its only true whan there is a string inside the p element
Now if you want to removethe br tag , then you can do this,
https://jsfiddle.net/joL9xh2r/1/
$(ele).html($(ele).text())
But, Remember this will remove all the html tags inside, for Example https://jsfiddle.net/joL9xh2r/2/,
here you have
<p id='x'>
"Some text"
<br/>
<b>abc</b>
</p>
A bold tag within p , so the above solution, and the one suggested by rorry will remove the b tag as well.
The best way to remove only br this would be
https://jsfiddle.net/joL9xh2r/3/
$('p').each(function(i,ele){
if($(ele).text().replace(/\s/g, '').length>0)
{
alert($(ele).attr('id')+' has string');
$(ele).find('br').remove();
}
})

Related

javascript - convert font element to span element using regex

I want to convert <font> element to <span> element like this using regex:
Input:
[some strings...]<span [something]></span><font ...>[sometext]</font>[some strings...]
Output:
[some strings...]<span [something]>[sometext]</span>[some strings...]
Note: The input/output is a string.
In shortly, I want to remove the <font> element and move the contents of that into <span> element keeping the attributes of the <span> element.
I've tried this:
const rx = /<span(.*?)><\/span>([^<\\s]+?|\\s*)<font(?:\\s+[^>]*)?>(.*?)<\/font>/gi;
inputStr.replace(rx, function(match, p1, p2, p3) { return `${p2}<span${p1}>${p3}</span>`; });
However it doesn't work.
Can anyone help me?
I also agree with #skyboyer, this is not the best way, but if you can use regexp only or if this is a one-time task, you can use a class group specifing to take all chars that are not ">", in this way you can take all the params of the tag span and use it in the font:
var text = 'Some text... <span style="color:red"></span><font style="margin:10px">Hi there!</font> other text <span style="color:blu"></span><font style="margin:10px">doh!</font> final text';
console.log(text.replace(/<span([^>]*)><\/span><font[^>]*>(.+?)<\/font>/gi,'<span$1>$2</span>'));
edited in order to match other tags inside (except other s, obviously)
Use any ID or class selector if possible, I have used here tag name just for example, if you have a Id selector then remove [0] from code.
This or with some modification should work for you
document.getElementsByTagName("font")[0].replaceWith('<span>' + document.getElementsByTagName("font")[0].innerHTML +'</span>')
Using Jquery,
$("YOUR_DOM_SELECTOR").replaceWith('<span>' + $("YOUR_DOM_SELECTOR").html() +'</span>')

How do get contents of a p element one at a time

Using jQuery, I need to parse the contents of each <p> tag individually and then replace the text with the new text.
The code at the moment looks like:
str = $('p').text();
str = str.replace('yadayada','yada');
$('p').text(str);
This is currently getting the contents of all the <p> tags, concatenating them then replacing the massive block of text into each <p> which is close but not quite what I'd like it to do.
Is there a way to get the contents of each <p> block one at a time and replacing it with only it's contents? I do not know what ids or classes are being applied to them hence the need to use the generic tag.
Any help is much appreciated! :)
Use the text(fn)
A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.
$('p').text(function(_ text){
return text.replace('yadayada','yada');
});
Use the text() version that accepts a callback as the second argument and return the replaced content from the callback
$('p').text(function(i, str) {
return str.replace('yadayada', 'yada');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>yadayada-1</p>
<p>yadayada-2</p>
<p>yadayada-3</p>
<p>4</p>
You can use .each method on the colletion:
$('p').each(function (pEl) {
var text = pEl.textContent;
});

Javascript : Replace Detect a string and replace html in a div after changing color

I am trying to change color of a part of strings. I have a list of DOM elements, and for each of them, the text can contain some hashtags. I would like to put in color all hashtags words which could be found in the text.
Here is the begin of the code :
var listOfText = document.getElementsByClassName("titleTweet");
for (var nodetext in listOfText) {
var divContent = listOfText[nodetext].innerHTML;
if (divContent.indexOf("#") !== -1) {
// Do job here
}
}
For example, divContent can be equals to "Hello my #friends ! How are you ?"
I would like to update the dom elements to put in red color the word "#friends".
I don't know how to do that using javascript or jQuery.
You can use a regexp to find the hastags and wrap them with html. Then use the .html() method to replace the original element's html with the new string.
Example snippet
$('#myDiv').replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
Working example - http://jsfiddle.net/4p4mA/1/
Edited the example to work on all divs on the page.
Note: This will only work so long as your element only contains text, because it is replacing all the child nodes with its text value.
use regex for this, find text having hashtag and replave that in span tag for each element.
$('.titleTweet').each(function(){
var $this=$(this);
$this.html($this.text()
.replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
});
See demo here
.innerHTML is a poor basis to starting replacing text. You'll want to navigate down to the text nodes and use .nodeValue to get the text. Then you can start splitting up the text nodes.

Add actual HTML elements to PRE/CODE contents

I'm trying to create a quick/dirty way to add some syntax highlighting for pre/code tags in html using javascript.
The problem i'm running into, is that if i edit either the text() or html(), I get escaped content. That is, the added tags render as pre/code, or i get a bunch of eascape characters.
Consider the following html:
<pre>
<code class="target">
public interface __iIFoo { }
public class __tBar : __iIFoo { }
var list = new List__/__iIFoo\__();
</code>
</pre>
The goal here is to replace occurrences of __iIFoo with:
<span class="interface">IFoo</span>
So that it can be highlighted with css. And of course, when it's rendered, I don't want to see the actual SPAN tag.
Here's what I've tried:
$(function(){
var iPatt = /__i\w+/g
$.each($(".target").text().match(iPatt), function(i,match){
var replace = '<span class="interface">'+match.substring(3)+'</span>';
$(".target").text(function(){
return $(this).text().replace(match, replace);
});
});
});
This works, BUT, the span tags I'm adding show up in the rendered content e.g. they are just like all the other pre code. I don't want to see it!
Use .html() instead of .text(). When you use .text(), the value is the literal text that you want users to see, so it replaces special HTML characters with entities so they'll show up literally.
DEMO
.text() treats value as text and .html() render it as html content
$(".target").html(function () { //replace text with html
return $(this).text().replace(match, replace);
});
Try using it with html instead:
$(function(){
var iPatt = /__i\w+/g
$.each($(".target").text().match(iPatt), function(i,match){
var replace = '<span class="interface">'+match.substring(3)+'</span>';
$(".target").html(function(){
return $(this).text().replace(match, replace);
});
});
});
As I said in my comment, change the html rather than the text (fiddle).
As a side-note, it's worrisome that you're completely overwriting the contents of .target every time you encounter a match. You should take advantage of RegExp capture groups and perform only one assignment.
(function () {
var iPattern = /__i(\w+)/g,
iTemplate = "<span class='interface'>$1</span>";
$(".target").each(function () {
this.innerHTML = this.innerHTML.replace(iPattern, iTemplate);
});
})();

Why JavaScript converts my < into >

JavaScript converts my < into >. I want to alert it but my message is with encoded marks like ##&*()}{>?>? - how to display it normally but prevent from executing as HTML code?
<span id="ID" onClick="alertIt(this.id);">
<p>Some string with special chars: ~!##&*()}{>?>?>|{">##$#^#$</p>
<p>Why when clicked it gives something like this:</p>
<p>'<br>
Some string with special chars: ~!##&*()}{>?>?>|... and so on
<br>'</p>
</span>
<script type="text/javascript">
function alertIt(ID)
{
var ID = ID;
var content = document.getElementById(ID).innerHTML;
alert(content);
}
</script>
Use innerText instead of innerHTML. http://jsfiddle.net/WVf95/
Your problem is that you use the wrong approach to get the text to display with alert().
Some characters are illegal in HTML text (they are used for HTML tags and entities). innerHTML will make sure that text is properly escaped (i.e. you can see tags and escaped text).
If you want to see tag and text in alert(), there is no solution.
If you want only the text, then you will have to extract it yourself. There is no built-in support for that. It's also not really trivial to implement. I suggest to include jQuery in your page; then you can get the text with:
function alertIt(ID) {
alert($(ID).text());
}
Using textContent instaed of innerHTML or innerText is a solution.

Categories

Resources