How to search a text in jquery? - javascript

i have a question that if i want to search a perticular text in any page using jquery. what i don't want is that
<p id="1">iii</p>
<p id="2">i</p>
<p id="3">ibiib</p>
<p id="4">bb</p>
<p id="5">tina</p>
<script type="text/javascript">
console.log($("div:contains('i')"));
</script>
this above code gives me all paragraphs except id=4; but what i want is only paragraph with id=2 to be selected.
if there is a way to do that in javascript or any other library reply me...

Use $.filter.
This will return the divs, which contains just one i.
$('div').filter(function () {
return $(this).html() == 'i';
});

$('p').filter(function() {
return $(this).text() === 'i';
});

You can extend jQuery's selector engine to add a new one:
$.expr[':'].texteq = function( elem, i, match, array ) {
return $(elem).text() === match[3];
};
console.log($('p:texteq(i)'));
Example

$("p").each(function(a,b){
if ($(this).html() == 'i'){
console.log(a);
}
});
or
$("p").filter(function(){
return $(this).html() == 'i';
});

You can loop through the paragraphs and check if their content is the same as your desired content. I used a jQuery loop, you can use javascript if you want.
JSFIDDLE
$('p').each(function() {
if(this.innerHTML == 'i') doWhateverYouWant();
});

I would use a simple plugin for this:
$.fn.exactMatch = function(str) {
return this.filter(function() {
return $(this).text() === str;
});
};
$("p").exactMatch("i").css("border", "1px solid red");
You can try it here.

Related

What is the best way cross-browser to trim an element innerHTML?

What is the best way cross-browser to trim an element innerHTML?
jsFiddle: http://jsfiddle.net/6hk8z/
I am assuming you are getting confused with the html code that is not whitespace but merely rendered as such by the browser. See customised implementation below:
String.prototype.trimmed = function(){
return this.replace(
/^(\s| |<br\s*\/?>)+?|(\s| |<br\s*\/?>)+?$/ig, ' '
).trim();
}
updated jsFiddle
Use the DOM, not innerHTML which you would need to parse.
function trimContents(element) {
function iterate(start, sibling, reg) {
for(var next, c = element[start]; c != null; c=next) {
next = c[sibling];
if (c.nodeType == 1 && c.nodeName.toLowerCase() == "br"
|| c.nodeType == 3 && !(c.nodeValue = c.nodeValue.replace(reg, "")))
element.removeChild(c);
else
break;
}
}
iterate("firstChild", "nextSibling", /^\s+/);
iterate("lastChild", "previousSibling", /\s+$/);
}
(demo at jsfiddle.net)
Have you tried jQuery's $.trim()? See jQuery documentation for more details.

How to match two html elements

For example, I have
<div class="welcome_font">name</div>
and
<div id="nameho" style="color:#5AC7E6;">another-name</div>
I want to write an "if" statement in jquery/javascript where if "name" matches "another-name", then do something. How do I do that?
The .html() function grabs the inner html when using jQuery. So you could use the following to compare the two:
if ( $('.welcome_font a').first().html() === $('#nameho').html() )
{
...
}
let me know if that makes sense or if you have any questions :)
Try,
if( $('.welcome_font a').text() == $('#nameho').text() )
{
////Do something
}
Research first next time. You could get this with a simple search.
if($(".welcome_font a").text() == $("#nameho").text())
{
//To do
}
var name_1 = $('.welcome_font').text();
var name_2 = $('#nameho').text();
if(name_1===name_2) {
alert('yes');
} else {
alert('no');
}
Demo : http://jsfiddle.net/TSGqC/
or
var name_check = ($('.welcome_font').text()===$('#nameho').text()?true:false);
if(name_check) {
alert('yes');
}
Demo : http://jsfiddle.net/TSGqC/1/

jQuery - Check if the tag's content is equal to sometext then do something

Let's say I have many of these in my content div : <cite class="fn">blabla</cite>
How can I check every cite tag's content (in this case: blabla) with class fn to see if it equals to "sometext" then change it's color to red ?
Very simple.
$('cite.fn:contains(blabla)').css('color', 'red');
Edit: though that will match "blablablabla" as well.
$('cite.fn').each(function () {
if ($(this).text() == 'blabla') {
$(this).css('color', 'red');
}
});
That should be more accurate.
Edit: Actually, I think bazmegakapa's solution is more elegant:
$('cite.fn').filter(function () {
return $(this).text() == 'blabla';
}).css('color', 'red');;
You can make use of the amazing .filter() method. It can take a function as its parameter, which will reduce the jQuery collection's elements to those that pass its test (for which the function returns true). After that you can easily run commands on the remaining elements:
var searchText = 'blabla';
$('cite.fn').filter(function () {
return $(this).text() === searchText;
}).css('color', 'red');
jsFiddle Demo
You could potentially do something like:
$('cite.fn').each(function() {
var el = $(this);
if (el.text() === 'sometext') {
el.css({ 'color' : 'red' });
}
});
This fires a function against each cite that has the class fn. That function checks if the current cite's value is equal to 'sometext'.
If it is, then we change the CSS color (text-color) property to red.
Note I'm using jQuery in this example, as you've specifically tagged your question jQuery. Ignore the downvote, this was applied before I edited a typo that I'd made (el.val() rather than el.text())
Without jQuery:
var elms = document.querySelectorAll("cite.fn"), l = elms.length, i;
for( i=0; i<l; i++) {
if( (elms[i].innerText || elms[i].textContent) == "blabla") {
elms[i].style.color = "red";
}
}

How do I check if an HTML element is empty using jQuery?

I'm trying to call a function only if an HTML element is empty, using jQuery.
Something like this:
if (isEmpty($('#element'))) {
// do something
}
if ($('#element').is(':empty')){
//do something
}
for more info see http://api.jquery.com/is/ and http://api.jquery.com/empty-selector/
EDIT:
As some have pointed, the browser interpretation of an empty element can vary. If you would like to ignore invisible elements such as spaces and line breaks and make the implementation more consistent you can create a function (or just use the code inside of it).
function isEmpty( el ){
return !$.trim(el.html())
}
if (isEmpty($('#element'))) {
// do something
}
You can also make it into a jQuery plugin, but you get the idea.
I found this to be the only reliable way (since Chrome & FF consider whitespaces and linebreaks as elements):
if($.trim($("selector").html())=='')
White space and line breaks are the main issues with using :empty selector. Careful, in CSS the :empty pseudo class behaves the same way. I like this method:
if ($someElement.children().length == 0){
someAction();
}
!elt.hasChildNodes()
Yes, I know, this is not jQuery, so you could use this:
!$(elt)[0].hasChildNodes()
Happy now?
jQuery.fn.doSomething = function() {
//return something with 'this'
};
$('selector:empty').doSomething();
If by "empty", you mean with no HTML content,
if($('#element').html() == "") {
//call function
}
In resume, there are many options to find out if an element is empty:
1- Using html:
if (!$.trim($('p#element').html())) {
// paragraph with id="element" is empty, your code goes here
}
2- Using text:
if (!$.trim($('p#element').text())) {
// paragraph with id="element" is empty, your code goes here
}
3- Using is(':empty'):
if ($('p#element').is(':empty')) {
// paragraph with id="element" is empty, your code goes here
}
4- Using length
if (!$('p#element').length){
// paragraph with id="element" is empty, your code goes here
}
In addiction if you are trying to find out if an input element is empty you can use val:
if (!$.trim($('input#element').val())) {
// input with id="element" is empty, your code goes here
}
Empty as in contains no text?
if (!$('#element').text().length) {
...
}
Another option that should require less "work" for the browser than html() or children():
function isEmpty( el ){
return !el.has('*').length;
}
You can try:
if($('selector').html().toString().replace(/ /g,'') == "") {
//code here
}
*Replace white spaces, just incase ;)
document.getElementById("id").innerHTML == "" || null
or
$("element").html() == "" || null
Vanilla javascript solution:
if(document.querySelector('#element:empty')) {
//element is empty
}
Keep in mind whitespaces will affect empty, but comments do not. For more info check MDN about empty pseudo-class.
if($("#element").html() === "")
{
}
Are you looking for jQuery.isEmptyObject() ?
http://api.jquery.com/jquery.isemptyobject/
Here's a jQuery filter based on https://stackoverflow.com/a/6813294/698289
$.extend($.expr[':'], {
trimmedEmpty: function(el) {
return !$.trim($(el).html());
}
});
JavaScript
var el= document.querySelector('body');
console.log(el);
console.log('Empty : '+ isEmptyTag(el));
console.log('Having Children : '+ hasChildren(el));
function isEmptyTag(tag) {
return (tag.innerHTML.trim() === '') ? true : false ;
}
function hasChildren(tag) {
//return (tag.childElementCount !== 0) ? true : false ; // Not For IE
//return (tag.childNodes.length !== 0) ? true : false ; // Including Comments
return (tag.children.length !== 0) ? true : false ; // Only Elements
}
try using any of this!
document.getElementsByTagName('div')[0];
document.getElementsByClassName('topbar')[0];
document.querySelectorAll('div')[0];
document.querySelector('div'); // gets the first element.
​
Try this:
if (!$('#el').html()) {
...
}
Line breaks are considered as content to elements in FF.
<div>
</div>
<div></div>
Ex:
$("div:empty").text("Empty").css('background', '#ff0000');
In IE both divs are considered empty, in FF an Chrome only the last one is empty.
You can use the solution provided by #qwertymk
if(!/[\S]/.test($('#element').html())) { // for one element
alert('empty');
}
or
$('.elements').each(function(){ // for many elements
if(!/[\S]/.test($(this).html())) {
// is empty
}
})

jQuery replace all single character

I want to replace all characters in the textarea by a click using jQuery.
For example:
ə = e, ı = i, ...
Thıs ıs əxamplə
By clicking it should be:
This is example
$('textarea').html($('textarea').html().replace(/ə/g,'e'))
Adding on from Zikes
var replace_map={
"ı":"i",
"ə":"e"
};
$('textarea').click(function(){
var ret='';
$.each(this.value.split(''), function(i, str) {
ret += replace_map[str] || str;
})
this.value = ret;
});
DEMO
UPDATED EDIT
var replace_map={
"ı":"i",
"ə":"e"
};
$('textarea').click(function(){
this.value = $.map(this.value.split(''), function(str) {
return replace_map[str] || str;
}).join('');
});
UPDATED DEMO
HTML:
<textarea>Thıs ıs əxamplə</textarea>
JS:
var replace_map={
"ı":"i",
"ə":"e"
};
$('textarea').click(function(){
this.value = this.value.replace(/./g,function(str){
return replace_map[str] || str;
})
});
I don't think you really need jQuery for that other than perhaps to select the textarea element (and then only for a microscopic amount of ease).
Past that you should be able to use just string.replace on the textarea content:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

Categories

Resources