I am learning JavaScript objects and have set myself a little project to create a slider. Its worth noting I coming from a jQuery background so my problem may lie with the way I trying to select the elements. I have the following HTML:
<div class="slider-viewport" id="mySlider">
<div class="slides-container">
<div class="slide">1</div>
<div class="slide">2</div>
<div class="slide">3</div>
</div>
</div>
and the following JavaScript:
(function(window, document, undefined){
// code that should be taken care of right away
window.onload = init;
function init(){
// the code to be called when the dom has loaded
var slider = {
sliderViewport: document.getElementById('mySlider'),
slidesContainer: document.querySelectorAll(this.sliderViewport + ' .slides-container')
};
console.dir(slider.sliderViewport + ' .slides-container');
console.dir(slider.slidesContainer);
//Just testing to see if I can do something
slider.slidesContainer.style.color = 'blue';
}
})(window, document, undefined);
When I view Chrome Dev Tools I get the following:
[object HTMLDivElement] .slides-container
objects.js:16 NodeList[0]
objects.js:18 Uncaught TypeError: Cannot set property 'color' of undefined
The first console.dir seems to return the element I am after. I'm not sure what the second console.dir is returning and also why I get an error of undefined. Please can you give me a steer on where I am going wrong?
Many thanks in advance.
querySelectorAll() expects a string as parameter to evaluate as a CSS selector. You can't concat a HtmlDivElement with a string, this is your first problem. The second one is that the querySelectorAll() returns a NodeList as you can see on the console. The problem is that the list is empty.
You may want to try this:
var slider = {
sliderViewport: document.getElementById('mySlider')
}
slider.slidesContainer: slider.sliderViewport.querySelectorAll('.slides-container');
I didn't tested it, but it should works as described here.
querySelectorAll and querySelector gets a string parameter (css selector):
var slider = {
sliderViewport: document.querySelector('#mySlider'),
slidesContainer: document.querySelector('#mySlider .slides-container')
};
Related
I can't understand why I am getting this error:
Uncaught TypeError: Cannot read property 'appendChild' of undefined
Here is my code:
//create new div element, append it to the body, give it an ID and a Class.
const container_clause_1 = document.createElement("div");
document.body.appendChild(container_clause_1);
container_clause_1.setAttribute("id", "container_clause_1");
container_clause_1.classList.add("cc1");
console.log(container_clause_1);
//returns <div id="container_clause_1" class="cc1></div>"
const cClause1 = document.getElementById("container_clause_1");
console.log(cClause1);
//returns <div id="container_clause_1" class="cc1></div>"
const right_clause_1 = document.createElement("div");
console.log(right_clause_1); //returns <div></div>
document.cClause1.appendChild(right_clause_1); //Error occurs here!
I don't understand what is undefined in this situation. cClause1 is define. right_clause_1 is also defined. Granted, it's an empty div at this point, but that is what I am trying to do - add the div and then I can add the class and id, etc.
Also, I don't see any typos.
Also, if I replace document.cClause1.appendChild(right_clause_1);
with document.body.appendChild(right_clause_1); it works fine. Except that I don't want it inside the body, but rather, inside the container_clause_1 div.
I can't use JQuery for this. "Why not" is not really germane to the question. I have my reasons. Just understand that I can't use JQuery.
Well that was so obvious - after everyone started pointing out what I did wrong! Thanks for the answers!
Just another thing that this pointed out to me:
I can eliminate the variable cClause and just use container_clause_1
so my code is shorter!
const container_clause_1 = document.createElement("div");
document.body.appendChild(container_clause_1);
container_clause_1.setAttribute("id", "container_clause_1");
container_clause_1.classList.add("cc1");
const right_clause_1 = document.createElement("div");
container_clause_1.appendChild(right_clause_1);
right_clause_1.setAttribute("id", "right_clause_1");
right_clause_1.classList.add("r1");
Why have "document." in this line?
document.cClause1.appendChild(right_clause_1);
Surely you only need:
cClause1.appendChild(right_clause_1);
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.
I am trying to get a div that is inside another div, since the id of the second div is variable, i use
var wrappingdiv = document.getElementById('divId')
to get the wrapping div then
var insidediv = wrappingdiv.getElementsByTagName('div')
but i get the getElementsByTagName is not a function error, i guess the syntax is wrong, could you guys put me in the right direction?
Thanks in advance.
Edit : I will correct myself, I am trying to get the body of a gmail email, so :
var element = content.document.getElementsByClassName("ii gt m13fbe3a51e95e196 adP adO");
it returns an object xraywrapper[object htmlcollection]
Edit 2 :
I am using mozilla firefox, and i am developing my own extension, to access source code of Google mail i use simple javascript (content.document...)
If you doesn't have any element with the id divId then wrappingdiv will be equal null:
And when trying to get null.getElementsByTagName you will get a type error:
TypeError: Cannot read property 'getElementsByTagName' of null
In
var element = content.document.getElementsByClassName(
"ii gt m13fbe3a51e95e196 adP adO");
getElements <- the s means this returns multiple elements (in a list-like collection), not just one element.
You might just want to pick out the first one it found.
var element = content.document.getElementsByClassName(
"ii gt m13fbe3a51e95e196 adP adO")[0];
There is also a small risk that it might not be m13fbe3a51e95e196 on every page, or forever. So perhaps you should generalise your search a bit. How about just searching for class "adP"?
The syntax isn't wrong. document.getElementById('divId') probably just fails to match the id of any existing element, so it returns null (which doesn't have a getElementsByTagName method).
DEMO
var wrappingdiv = document.getElementById("divId");
var insidediv = wrappingdiv.getElementsByTagName('div');
var i = 0;
for(i=0;i<insidediv.length;i++)
alert(insidediv[i].innerHTML);
The following function doesn't work for some reason. Can someone see what the problem is?
function checkMaxLen(txt, maxLen) {
var actualLen = txt.value.length;
var remain = maxLen - actualLen;
document.getElementById('remainChar').Value = remain;
}
<input type="text" id="remainChar" runat="server" value="500"/>
Whenever I try to run the function, I get this error:
Microsoft JScript runtime error: Unable to set value of the property 'Value': object is null or undefined
Check the ID of the input in your final HTML. Since you have runat="server" ASP.NET is likely adding its typical container prefixes.
Main Problem: There is no Javascript getElementById issue, but rather a problem with feeding the right id into getElementById (caused because ASP.NET feels free to change the ids of runat="server" elements) (covered by the accepted answer). This is what caused the error the OP reported:
Microsoft JScript runtime error: Unable to set value of the property 'Value': object is null or undefined
This was because getElementById was given a non-existent id and returned null.
Another Problem: The second problem was indeed a Javascript problem, but not related to getElementById either. Javascript is case sensitive, so trying to set the value property of a input element's DOM object cannot be done by trying to set But even if the (non-existent) Value property.
Solution:
The correct code that solves both problems follows:
function checkMaxLen(txt, maxLen) {
var actualLen = txt.value.length;
var remain = maxLen - actualLen;
document.getElementById('<%= remainChar.ClientId%>').value = remain
}
Note: Thanks go to Ian for pointing out an important oversight in my original answer.
case sensitive:
document.getElementById('remainChar').value
.Value should be .value, script should be executed after appears in the source or after the DOMReady event has been fired.
also since this is asp.net the id attribute of the box will not be "remainChar" but transformed into something else.
so you either need to find out what the final id will be or remove the runat="server" attribute
<html>
<body>
<input type="text" id="remainChar" value="500"/>
<script>
function checkMaxLen(txt, maxLen) {
var actualLen = txt.value.length;
var remain = maxLen - actualLen;
document.getElementById('remainChar').value = remain;
}
checkMaxLen({value:""},20);
</script>
</body>
</html>
Below is simple code I am using. But why it's not working. giving javascript error.
function postcommnet(wallid) {
var txtboxid='commentdata_'+wallid;
var commentdata=document.getElementById(txtboxid).value
}
error is : document.getElementById(txtboxid) is null.
Please help.
This is one of the few cases where the error is telling you what's wrong:
"document.getElementById(txtboxid) is null."
This means, essentially, that the value of the above is null. This means that getElementById did not find an element with the ID you provided.
Check that the value of txtboxid is correctly an id on one of the DOM's elements. Your error message means that the element is not retrieved and thus the value is null.
It cannot find the element with the id. I have checked the code is working if there is an element with the given id.
This actually works:
<html>
<body>
<input value="lol" id="commentdata_1"/>
<script type="text/javascript">
function postcomment(wallid) { var txtboxid='commentdata_'+wallid;
var commentdata=document.getElementById(txtboxid).value
}
postcomment(1);
</script>
</body>
</html>
The id may not exist on your page, its worth checking.
The following checks to see if the id exists. If it does not exist it will tell you the id its trying to use.
function postcommnet(wallid) {
var txtboxid='commentdata_'+wallid;
if(document.getElementById(txtboxid)){
var commentdata=document.getElementById(txtboxid).value
}
else{
alert('the id - ' + txtboxid +' does not exist');
}
}
I'd suggest using Firefox/Firebug and setting a breakpoint inside your function, then check that the value for wallid is what you expect and, if necessary, examine the live HTML to ensure that the element does, in fact, exist.