This is my first time working with .addClass().
In my project, I need to display notifications on a dummy phone screen (an image of iPhone). A notification has a title and some description. This title and description is coming from a form on the same webpage. To compose this notification, I am doing:
var notificationText = $('#title').val().addClass('title') + plainText.addClass("description");
However, I am getting an error:
TypeError: $(...).val(...).addClass is not a function
What am I doing wrong here?
UPDATE:
So, as per the overwhelming requests, I did:
var notificationText = $('#title').addClass('title').val() + plainText.addClass("description");
However, I am getting an error:
Uncaught TypeError: Object sss has no method 'addClass'
jsFiddle
UPDATE 2: I do not need to style the description, so I removed the class related to it. Please see my updated fiddle. Now the problem is that the text in title is getting bold instead of the one copied in #notifications. It is not getting styled as per the CSS.
So many answers in so little time... sigh
I gathered what I think you wanted. Try this one:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/7b3j2/13/
$(document).ready(function(){
CKEDITOR.replace( 'description' );
$('#title').focus();
$('form').submit(function(event){
event.preventDefault();
var html=CKEDITOR.instances.description.getSnapshot();
var divEle=document.createElement("DIV");
divEle.innerHTML=html;
var plainText=(divEle.textContent || divEle.innerText);
var $title = $('<span></span');
$title.addClass('title');
$title.text($('#title').val());
var $desc = $('<span></span');
$desc.addClass('description');
$desc.text(plainText);
$('form').append($title);
$('form').append($desc);
});
});
You can obviously chain some of the span operations, but I left them readable for now. Shorter version would look like:
var $title = $('<span></span').addClass('title').text($('#title').val());
var $desc = $('<span></span').addClass('description').text(plainText);
$('form').append($title).append($desc);
As you probably know by now, but for completeness, the initial errors were the result of trying to apply jQuery methods to string objects. This solution creates new jQuery span objects that can then be styled and appended to the form.
You are trying add class to a value, which is definitely is not a jQuery object
Try this instead:
$('#title').addClass('title').val()
addClass can only be performed on jQuery objects and returns a jQuery object - that's what makes it chainable. You can't add a class to a string.
So, in this code, there are actually two mistakes:
1) plainText.addClass - plainText is a string, and not a jQuery object. You must add the class to the element you created (in your case, the divEle element), but, since addClass only works with jQuery objects, you must convert your div to a jQuery element first. You can accomplish this by doing the following:
$(divEle).addClass('description');
2) addClass returns a jQuery object, so you can't concatenate it with a string.
EDIT: Just realized that you're appending notificationText (which is a string) to the DOM. You must convert it to a div and add the div to the DOM.
jsFiddle: http://jsfiddle.net/7b3j2/17/
Mistake done by you:
<div id="title"><div>
$('#title').val().addClass('title')
->Now here $('#title').val() will give that particular element value.
->$('#title').val().addClass() you are adding class to that value.
Use this:
$('#title').addClass();
As you cannot add class to element's value.
You should addClass to particular element as addClass internally will add attribute class to that element.
So finally solution becomes:
$('#title').addClass('title').val()
For adding a class, you have to use
$('#title').addClass('title');
If you want to get the value, you can use
$('#title').addClass('title').val()
While addClass and val() are both methods on the jQuery object, val() is not chainable like addClass is. When you do $('#title').val() you aren't returning the object, you're only returning the string value of the element.
Use this instead:
$('#title').addClass('title');
And if you still need to get the value:
$('#title').addClass('title').val();
The reason why plaintext is producing an error is because you're trying to use the jQuery addClass method on a DOM node that has been natively created with document.createElement("DIV");. This will not work. To get it to work you either need to to define your new element with jQuery:
var divEle = $('<div></div>');
and then add the class:
divEle.addClass('description');
Or use the native classname method to add the class to the DOM node:
divEle.className = divEle.className + " description";
Try putting addClass first
$('#title').addClass('title');
Update
To get the code fully working you should split up the line like so.
var notificationText = $('#title').val() + ' ' + plainText;
$('#title').addClass('title');
$(plainText).addClass("description");
Fiddle
Final Update
So what we actually want to do here is:
get the values of the content
append them on submit and style the appended text
Example
// Get the text.
var notificationText = $('#title').val() + ' ' + plainText;
// Append to form.
$('form').append('<span class="summary">' + notificationText + '</span>');
// CSS styling
.summary {
display:block;
font-weight: bold;
}
See Fiddle
Considering #title is the id of the element.
You can directly need to add classname to it.
$('#title').addClass('className');
where className is the name of the class.
because you are trying to add class over value instead of element.
$('#title').val().addClass('title') //it is wrong
replace it with:
$('#title').addClass('title')
if plainText is not an element object you initialize by
var plainText = $('#anotherId');
will also cause this error.
Related
There are several functions to get DOM document elements e.g. .getElementById(), .getElementByName() etc. but I do not see any function which would allow to get element by type.
Is there some mechanism to do it?
You can use the getElementsByTagName() function to get all elements by their tag name.
I.e. getElementsByTagName("div") will return all <div>'s.
CSS selectors via .querySelectorAll are most powerful.
let p = document.querySelectorAll("p");
console.log(p[0].innerHTML + " and " + p[1].innerHTML);
<p>asdf</p>
<span>fdafsdf</span>
<p>kjkjkj</p>
You can get all elements by the type with 'document.querySelectorAll()' method.
As an example, you can get all the 'input' elements with type 'text' as follows.
document.querySelectorAll('input[type="text"]')
I want to access a object by using $('id'), but cannot success.
here's my code :
function jumptopage(myOffset, mySilder, table) { // javascript
...
var oPageSlice = $(recordsPageName); // -> stop
var myURL = $("jumptourl").value; // -> -> stop
...
}
The program always stops at that two lines.
recordsPageName is 'records_page', and both "jumptourl" & 'records_page'
are really exist.
I can use
"var oPageSlice = document.getElementById(recordsPageName);"
to replace
"var oPageSlice = $(recordsPageName);"
And it will work.
But I still want to find the reason.
p.s. The problem also can be reproduced in the following .
It seems the same issue in my php code.
html[] = '<input type="button"
onClick="setPerPageRecs($(\''.$this->aName['records_page'].'\')...'
In this situation, setPerPageRecs doesn't be called when i click the button
it seems that $(\''.$this->aName['records_page'].'\' doesn't correspond
to the object.
You need to add # to get a element by id. like this:
$("#id");
Look at Selector #ID. It lacks the # to select an ID
$("#jumptourl").val();
you missed # character to get element by id and use val() instead of value:
$("#jumptourl").val()
---^
to access by class use $('.elementClass')
I presume $("jumptourl") is meant to be referencing an id or a class?
You need to use a . for a class, or a # for an id.
E.g.
$(".jumptourl") or $("#jumptourl")
Here I have get one error in JavaScript div_element is null or not an object.
I have given my code below:
function showLoading(id) {
div_element = $("div#" + id)[0];
div_element.innerHTML = loading_anim; // Error in this line
}
When I am debugging my script but it's working fine in other browsers including IE 8, but it's not working in IE 7. I don't understand what exact issue occur in this script.
First of all, you dont need to put a tag name infront of the jQuery, unless you have other elements with exact same id on other elements, in other pages.
Next, your statement div_element.innerHTML = loading_anim; is correct. So, the only explanation is that, there is no element with that ID, in the DOM.
Finally, since you are usign jQuery already, no need to mix up native JS and jQuery to create a dirty looking code.
function showLoading(id) {
div_element = $("#" + id);
console.log(div_element); //check the console to see if it return any element or not
div_element.html(loading_anim);
}
I think you don't select anything with your jquery selector (line 2)
try to display
id
"div#" + id
$("div#" + id)
$("div#" + id)[0]
You can use firebug javascript console or a simple alert like this:
alert($("div#" + id)[0]);
And see if you must id or class on your div ( use # or . selector)
I suppose, that nic wants to display some loader GIF animation, I confirm, that nic must use jQuery .html() method for DOM objects, and tusar solution works fine on IE6+ browsers. Also (it is obvious but anyway) nic must assign a value to loading_anim variable in script, lets say: var loading_anim = $('#loader').html(); before assigning its value to div_element.
Use .html() for jQuery objects. innerHTML work for dom objects, they wont work for jQuery objects.
function showLoading(id) {
div_element = $("div#" + id);
$(div_element).html(loading_anim); // Provided `loading_anim` is valid html element
}
I tried to use the method data (jQuery 1.7.1) in this code:
var q = '<div class="form-error-marker"></div>';
var t = $(q).data('message', message).insertAfter(el);
and it does not work.
Note that this works:
var t = $(q).attr('data-message', message).insertAfter(el);
Why does the first variant not work?
EDIT: insertAfter works correctly and new div is added after el (which is instance of one element which I get by getElementById() function; long story short I have a library that I extend).
When I say 'it does not work' I mean that the attribute 'data-message' is not stored.
Using data like that sets an arbitrary piece of data for this node; it doesn't add a new data- attribute. Just add the attribute with the attr function, and then access it with data
var q = $('<div class="form-error-marker"></div>').attr("data-message", message);
Now access it like this:
var message = q.data("message");
Here's a fiddle
When you use jQuery.data you don't change element attributes, instead your data saved in $.cache.
So if you want to change element attributes use jQuery.attr, when you want to save some info use jQuery.data
I have a function
function toggleSelectCancels(e) {
var checkBox = e.target;
var cancelThis = checkBox.checked;
var tableRow = checkBox.parentNode.parentNode;
}
how can I get a jQuery object that contains tableRow
Normally I would go $("#" + tableRow.id), the problem here is the id for tableRow is something like this "x:1280880471.17:adr:2:key:[95]:tag:". It is autogenerated by an infragistics control. jQuery doesn't seem to getElementById when the id is like this. the standard dom document.getElementById("x:1280880471.17:adr:2:key:[95]:tag:") does however return the correct row element.
Anyways, is there a way to get a jQuery object from a dom element?
Thanks,
~ck in San Diego
Absolutely,
$(tableRow)
http://docs.jquery.com/Core/jQuery#elements
jQuery can take the DOM elements, try with:
$(tableRow)
or
$(checkBox.parentNode.parentNode)
You should be able to pass the element straight in, like this:
$(tableRow)...
I have tested this by creating a reference to a div, then passing it straight into jQuery and it creates the jQuery object for you.
You can call the jQuery function on DOM elements: $(tableRow)
You can also use the closest method of jQuery in this case:
var tableRowJquery = $(checkBox).closest('tr');
If you want to keep using your ID, kgiannakakis (below), provided an excellent link on how to escape characters with special meaning in a jQuery selector.
See this for how you should escape the id.
try:
var r = $(document.getElementById("XXXX----ID Of Your Row----XXXX"));
now, if document.getElementById doesn't return undefined you can use r as any regular jquery object.