<p></p> // return true
<p>something</p> //return false
I thought of using jquery's contains() but I think there's a better way of doing it in pure js?
You can use either childNodes or children in plain JS. Both return an array-like collection containing the children of an element. Both collections have a length property.
Note that both properties are live collections. You might want to shallow-copy them into an array. Here's an example of getting all children of body.
var hasContent = Array.prototype.slice.call(document.body.children).length;
I would use the old innerHTML to avoid JQuery like you want:
function hasSomething(id) {
var element = document.getElementById(id);
if (element && (element.innerHTML || '').trim())
return true;
else
return false;
}
return element.innerHTML.trim().length == 0;
Assume you've got a tag with id mydiv
<p id='mydiv'>Something</p>
if($('#mydiv').is(':empty'))
or
if($('#mydiv:empty').length)
can check whether it's empty.
SOmething like:
var myTextField = document.getElementById('myText');
if(myTextField.value != "")
alert("nothing")
else
alert("Would you please enter some text?")
}
Check function in the code below will do the job, You just need to call it. I have attached code in both jquery and javscript.
HTML :
<p id="data">Some text</p>
Jquery :
<script>
function check()
{
var len= $("#data").text().length;
if(len==0)
return true;
else
return false;
}
$(document).ready(function(){
document.write(check()); // call check function
});
</script>
Javascript:
<script>
function check() {
var x = document.getElementById("data").innerHTML;
if(x.length==0)
return true;
else
return false;
}
</script>
Related
Below is a sample structure from which i'm trying to get the specific value of custom attribute
<div id="123"></div>
<div id="456"></div>
<div context="james"></div>
Below is how i'm trying to fetch, but it always returns false.
if ( $('div').attr('context') == 'james' ) {
alert("yes");
} else {
alert("no");
}
The call to $('div').attr('context') will only grab the first div found in the DOM and check it's value. Since it doesn't have that attribute you get false. Instead you will want to iterate over all your div's and check each one. For example:
var found = false;
$('div').each(function( ) {
if($(this).attr('context') === 'james') found = true;
});
if(found) alert("yes");
else alert("no")
You could also use .filter:
if( $('div').filter(function(){ return $(this).attr('context') === 'james' }).length )
alert("yes");
else
alert("no");
Note: If you used data-context="james" you would use the .data() method rather than .attr().
Simply let jQuery do the filtering for you. Also, this can be done with plain old vanilla javascript pretty easily:
// Select by attribute
var theDiv = $("div[context='james']");
// If we have something here...
if(theDiv.length){
console.log(theDiv.text() );
} else {
console.log("Nope, not found.");
}
// We can use this same selector with plain javascript...
let theSameDiv = document.querySelector("div[context='james']");
// In this event, however, we access the text differently.
if(theSameDiv){
console.log("Found without jQuery!", theSameDiv.textContent);
} else {
console.log("Rats...");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="123">the first div</div>
<div id="456">div the second</div>
<div context="james">I'm 'Enry the Eighth, I Am!</div>
I am new to jQuery and I can't see where my code is wrong. I am trying to get an element with the id of custom-logo-video to change its innerHTML with an if statement (if it is "" or blank etc). However it is not working. What am I doing wrong?
$(document).ready(function(){
var a = $("#custom-logo-video");
if (!a.trim()) {
// is empty or whitespace
a.innerHTML("easy");
} else {
a.innerHTML("hard");
}
});
you can try:
$(document).ready(function () {
var a = $('#custom-logo-video').html();
if (!$.trim(a)) {
// is empty or whitespace
$('#custom-logo-video').html("easy");
} else {
$('#custom-logo-video').html("hard");
}
});
A few issues with the code
var a = $(#custom-logo-video);
selection requires quotes around it
var a = $('#custom-logo-video');
When you use jquery to select, you have a jQuery object so innerHTML won't work, you want to use either .html() or .text() to get the inner text. Here is how I fixed it.
$(document).ready(function(){
var a = $('#custom-logo-video');
if (!a.html()) {
// is empty or whitespace
a.html("easy");
}else{
a.html("hard");
}
});
You can read more here: https://learn.jquery.com/using-jquery-core/selecting-elements/
You're using innerHTML which isn't necessary since you're using jQuery. .html() will suffice.
Try this:
$(document).ready(function(){
var a = $("#custom-logo-video");
if ( !a.html().trim() ) {
// is empty or whitespace
a.html('easy');
}
else {
a.html('hard');
}
});
EDIT: fixed typos and logic in code.
Try this as well,
$(document).ready(function () {
var a = $('#custom-logo-video').html();
(a !== null && a.trim().length > 0) ? a.html('hard') : a.html('easy');
});
Try this:
$(document).ready(function(){
var a = $('#custom-logo-video');
if (!a.trim()) {
// is empty or whitespace
a.text("easy");
} else {
a.text("hard");
}
});
Try this code:
$(document).ready(function(){
var a = $("#custom-logo-video");
// To check if the node is empty or not I am
// calling jQuery api is(':empty')
if (a.is(':empty')) {
// is empty or whitespace
// To replace the innerHTML of a node you call a .html() jQuery api
a.html("easy");
} else {
a.html("hard");
}
});
Working Example
I've got the following bit of code (using JQuery) that I've written for a project. The idea is to have a function that you can attach to an element within an "item" div and it will return the id of that div. In this case, the div id would be item-[some item primary key value]. This function works probably 9/10 times, but every once in a while it will get to the else else case and return false. I've verified through the console that the input for selector is the exact same JQuery $() item in both the success and fail cases.
I'm relatively new to JavaScript, so there may be something obvious I'm missing, but this is some really unusual behavior.
var recursionCounter = 0;
function getElementID(selector, recursionDepth, searchString){
console.log(selector);
var elementID = selector.attr("id");
if(elementID === undefined){
elementID = "";
}
if(elementID.indexOf(searchString) !== -1){
elementID = elementID.split("-")[1];
return elementID;
} else {
if(recursionCounter < recursionDepth){
recursionCounter++;
return getElementID(selector.parent(), recursionDepth, searchString);
} else {
recursionCounter = 0;
alert("The element clicked does not have an associated key.");
return false;
}
}
}
Here is an example of code that calls this function, for some context.
$(document).on("click", ".edit-pencil-item", function(event) {
//Use helper function to get the id of the surrounding div then pass it to the function
var itemID = getElementID($(this), 10, "item-");
jsEditItem(itemID);
return false;
});
Thanks in advance for any help!
If you want to get the encapsulating element of your clicked element, and you know it should have an id starting with "item-" you should be able to do something along the lines of
$(this).closest('[id^="item-"]').attr('id')
Which says find this elements closest parent that has an id starting with "item-" and tell me its id.
I have the following structure:
<div id="campaignTags">
<div class="tags">Tag 1</div>
<div class="tags">Tag 2</div>
<div class="tags">Tag 3</div>
</div>
And I'm trying to match user input against the innerText of each children of #campaignTags
This is my latest attempt to match the nodes with user input jQuery code:
var value = "Tag 1";
$('#campaignTags').children().each(function(){
var $this = $(this);
if(value == $(this).context.innerText){
return;
}
The variable value is for demonstration purposes only.
A little bit more of context:
Each div.tags is added dynamically to div#campaignTags but I want to avoid duplicate values. In other words, if a user attempts to insert "Tag 1" once again, the function will exit.
Any help pointing to the right direction will be greatly appreciated!
EDIT
Here's a fiddle that I just created:
http://jsfiddle.net/TBzKf/2/
The lines related to this question are 153 - 155
I tried all the solutions, but the tag is still inserted, I guess it is because the return statement is just returning the latest function and the wrapper function.
Is there any way to work around this?
How about this:
var $taggedChild = $('#campaignTags').children().filter(function() {
return $(this).text() === value;
});
Here's a little demo, illustrating this approach in action:
But perhaps I'd use here an alternative approach, storing the tags within JS itself, and updating this hash when necessary. Something like this:
var $container = $('#campaignTags'),
$template = $('<div class="tags">'),
tagsUsed = {};
$.each($container.children(), function(_, el) {
tagsUsed[el.innerText || el.textContent] = true;
});
$('#tag').keyup(function(e) {
if (e.which === 13) {
var tag = $.trim(this.value);
if (! tagsUsed[tag]) {
$template.clone().text(tag).appendTo($container);
tagsUsed[tag] = true;
}
}
});
I used $.trim here for preprocessing the value, to prevent adding such tags as 'Tag 3 ', ' Tag 3' etc. With direct comparison ( === ) they would pass.
Demo.
I'd suggest:
$('#addTag').keyup(function (e) {
if (e.which === 13) {
var v = this.value,
exists = $('#campaignTags').children().filter(function () {
return $(this).text() === v;
}).length;
if (!exists) {
$('<div />', {
'class': 'tags',
'text': v
}).appendTo('#campaignTags');
}
}
});
JS Fiddle demo.
This is based on a number of assumptions, obviously:
You want to add unique new tags,
You want the user to enter the new tag in an input, and add on pressing enter
References:
appendTo().
filter().
keyup().
var value = "Tag 1";
$('#campaignTags').find('div.tags').each(function(){
if(value == $(this).text()){
alert('Please type something else');
}
});
you can user either .innerHTML or .text()
if(value === this.innerHTML){ // Pure JS
return;
}
OR
if(value === $this.text()){ // jQuery
return;
}
Not sure if it was a typo, but you were missing a close } and ). Use the jquery .text() method instead of innerText perhaps?
var value = "Tag 1";
$('#campaignTags').find(".tags").each(function(){
var content = $(this).text();
if(value === content){
return;
}
})
Here you go try this: Demo http://jsfiddle.net/3haLP/
Since most of the post above comes out with something here is another take on the solution :)
Also from my old answer: jquery - get text for element without children text
Hope it fits the need ':)' and add that justext function in your main customised Jquery lib
Code
jQuery.fn.justtext = function () {
return $(this).clone()
.children()
.remove()
.end()
.text();
};
$(document).ready(function () {
var value = "Tag 1";
$('#campaignTags').children().each(function () {
var $this = $(this);
if (value == $(this).justtext()) {
alert('Yep yo, return');)
return;
}
});
//
});
I have a (very) basic validation script. I basically want to check for any inputs with class .required to see if there values are a) blank or b) 0 and if so, return false on my form submit. This code does not seem to return false:
function myValidation(){
if($(".required").val() == "" || $(".required").val() == 0){
$(this).css({ backgroundColor:'orange' }) ;
return false;
}
}
Appending this function to my onSubmit handler of my form is not returning any results. Any light shed on this matter will be appreciated.
I am basically after a function that iterates through all the inputs with class .required, and if ANY have blank or 0 values, return false on my submit and change the background colour of all badly behaved inputs to orange.
Your code currently gets the .val() for the first .required, from the .val() documentation:
Get the current value of the first element in the set of matched elements.
You need to filter through each one individually instead, like this:
function myValidation(){
var allGood = true;
$(".required").each(function() {
var val = $(this).val();
if(val == "" || val == 0) {
$(this).css({ backgroundColor:'orange' });
allGood = false;
}
});
return allGood;
}
Or a bit more compact version:
function myValidation(){
return $(".required").filter(function() {
var val = $(this).val();
return val == "" || val == 0;
}).css({ backgroundColor:'orange' }).length === 0;
}
Try this jQuery selector:
$('.required[value=""], .required[value=0]')
You could also do it by defining your own custom jQuery selector:
$(document).ready(function(){
$.extend($.expr[':'],{
textboxEmpty: function(el){
return ($(el).val() === "");
}
});
});
And then access them like this:
alert($('input.required:textboxEmpty').length); //alerts the number of input boxes in your selection
So you could put a .each on them:
$('input.required:textboxEmpty').each(function(){
//do stuff
});