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/
Related
please help me with this code
this i a javascript code
not the actuall
var elements, searchText = "Open Help";
elements = YAHOO.util.Dom.getElementsBy(function (element) {
return (element.innerHTML === searchText) ? true : false;
}, "a", document);
if (elements.length > 0) {
//do something with elements[0]
}```
you are using get method on your form.Replace that with POST method
Your question is confusing and vague and I have no idea what you're trying to do, but with the input text you can just change the url with this:
window.location.href
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 do you make a JavaScript function have a false option, which makes sure the function doesn't execute?
Here's the code:
function deleteExtraRows(tableID){
tableID = '#'+tableID;
$(tableID+' tr').each(function(){
if($(tableID+' tr').length>1){
$(this).remove();
}
});
}
I want to also be able to give it a (false) option, so I can run deleteExtraRows(false), which will not make the function run. I know this seems kind-of backwards, but it would fit in the project I'm working on if I can do this.
Please help!
This should do the trick:
function deleteExtraRows(tableID){
if(tableID === false)
return;
....
}
It is important to use === as opposed to == since === checks the type as well. If tableID were 0 or an empty string, it would evaluate to true and return as well.
What you have should already work if there isn't an element on the page with an id of false.
Do it like this
function deleteExtraRows(tableID){
if(!tableID)
return;
tableID = '#'+tableID;
$(tableID+' tr').each(function(){
if($(tableID+' tr').length>1){
$(this).remove();
}
});
}
just do return
return stops the execution of the function..
function deleteExtraRows(tableID, valid ){
if(!valid)
return;
tableID = '#'+tableID;
$(tableID+' tr').each(function(){
if($(tableID+' tr').length>1){
$(this).remove();
}
});
}
Try this:
function deleteExtraRows(tableID, doWork){
if (!doWork) return;
tableID = '#'+tableID;
$(tableID+' tr').each(function(){
if($(tableID+' tr').length>1){
$(this).remove();
}
});
}
where is it being called?
just do:
if(!!tableID) deleteExtraRows(tableID);
I'd suggest Greg's answer above, but thought that you can optimize your code a bit by rewriting it like this:
function deleteExtraRows (tableID) {
if (tableID === false) {
return;
}
$('#' + tableID).find('tr:not(:last)').remove();
}
... unless I'm misinterpreting your code there.
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";
}
}
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
}
})