Setting html using jQuery on li element results in error - javascript

Here is jsfiddle link - http://jsfiddle.net/howg59sg/5/
<div id='test1'>
<ul>
<li id="li1" friendName="foo">test 1</li>
<li id="li2" friendName="bar">test 2</li>
</ul>
</div>
function myclick() {
alert("clicked");
var elemId = "#li1";
var elemCollection = jQuery(elemId);
alert("len = " + elemCollection.length);
if (elemCollection.length) {
var selectedElem = elemCollection[0];
alert("id of the element to work on " + selectedElem.attributes["id"].value);
var stringToReplaceWith = "testing";
alert("friendname = " + selectedElem.attributes["friendname"].value);
//alert("html value of selected elem = " + selectedElem.html());
selectedElem.html(stringToReplaceWith);
} else {
alert("none");
}
}
As you can see, I am trying to update the html content of a li element using jQuery. This results in following error:
Uncaught TypeError: undefined is not a function
I am able to get attributes on this li element but html() setter fails. Even getter fails as well which i have commented out in the code for now...
Does anyone know, What might be wrong here?
Thanks for the help.

You get the error because selectedElem is not a jQuery object.
var selectedElem = elemCollection[0]; <-- gets the DOM node
selectedElem.html(stringToReplaceWith); <-- you treat it as a jQuery object
either use .eq(0) to get the element as jQuery instead of bracket notation and use .attr() to read the attributes Or wrap it with jQuery() or use innerHTML

Your issue is likely with this line:
var selectedElem = elemCollection[0];
That will give you a regular DOM element object instead of a jQuery object. DOM elements don't have the html() function like jQuery objects do. You can replace the whole function with just these lines of code:
function myclick(){
jQuery('#li1').html('testing');
}

The following line returns a native DOM Html element:
elemCollection[0];
If you want the first item in a collection as a jQuery element use first():
elemCollection.first();

Related

Get span value with jquery

I have tested every solution I have found on Internet, but none of them works.
I have this HTML:
<h4>Códigos disponibles:<span id="codesQuantity">#Model.ExternalCodesForThisProduct</span></h4>
And this Javascript:
$('#eCodesFrm').on('submit', function (e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
var availableCodes = $("#codesQuantity");
var totalCodesUsed = 0;
alert(availableCodes);
$('#eCodesFrm *').filter(':input').each(function () {
if (this.name.match(/.Quantity$/)) {
totalCodesUsed = totalCodesUsed + parseInt(this.value, 10);
}
});
But availableCodes is [object Object].
What am I doing wrong?
If you need the inner element try .html(). As long as it's plain text in there there shouldn't be a problem.
To get the text inside the <span> use .text():
jQuery("#codesQuantity").text() //or $("#codesQuantity").text() if $ is jQuery in your code.
The problem here is that you're assigning a jQuery object to your variable, and not the content of the element. To extract the text inside the <span>, you should use either .html() or .text(), and do this instead:
var availableCodes = $("#codesQuantity").text();

Looping through generated HTML with jQuery

I know if I wanted to bind events to generated HTML, I'd need to use something like .on(), but I've only used it when binding events like .click().
I'm creating a web app that applys a list of colors. Colors are generated from a JSON file. Once fetched, I add it to the page, with certain information contained in attributes. I'd like to do something with the new generated HTML, which is list-elements. But what console.log() is showing me is there is nothing in the parent ul. Even though on the page I see the newly added content.
Here's the entire code based around it.
var setColors = function(){
getColors = function(){
$.getJSON('js/colors.json', function(colors) {
$.each(colors, function(i, colors) {
//console.log(colors);
$('<li>', {
text: colors['color'],
'name' : colors['color'],
'data-hex' : colors['hex'],
'data-var' : colors['var']
}).appendTo('#picker');
})
});
addColors();
}
addColors = function(){
var el = $('#picker').children;
$(el).each(function(){
console.log($(this));
});
}
return getColors();
}
$(function(){
setColors();
});
addColors() is where I'm having trouble with. The error says 'Uncaught TypeError: Cannot read property 'firstChild' of null. How can I work with the newly generated HTML?
You are missing parentheses on the children method:
var el = $('#picker').children();
Also, if you want the addColor method to be executed on the newly generated html, then you must add a call to it after the html is generated, from within the getJSON callback method.
addColors = function(){
var el = $('#picker').children;
$(el).each(function(){
console.log($(this));
});
}
A few issues:
missing end semi-color
missing parentheses on .children()
children() returns a jQuery object, no need for $(el)
Updated:
window.addColors = function(){
var $el = $('#picker').children();
$el.each(function(){
// do stuff here, but could attach each() to above, after children()
});
};

jQuery, Object has no method 'innerHtml'

I asked a question a bit back and got some useful advice. I am trying to make a sortable list that allows the user to add a youtube url to the list. I have it set to take the id and put it in an array, I then want it to use the following javascript to append the video url and a "cue" link to the list:
_videoId = _videoUrl.replace(/^[^v]+v.(.{11}).*/,"$1");
//place the Videoid in an array
_videoList[_videoList.length] = _videoId;
var $new_element = document.createElement('li');
//set the id of the li element to match it's position in the array
var refId = _videoList.length;
$new_element = $('li').attr('id', refId);
var $link = $('a')
.attr('href', _videoUrl)
.innerHtml(_videoUrl)
.data('refId', refId) // add parent li's id for reference in click event
.appendTo( $new_element )
.bind( 'click', function(){
cue( $link.data('refId') );
return false; // prevent browser's default click event
});
$new_element.appendTo( container );
However it is giving me an error (in chrome)
Object [object Object] has no method 'innerHtml'
my HTML looks like this:
<div id="hostPanel">
<div id="videoList">
<ul id="sortable">
</ul>
</div>
Any help on getting this to work could be nice.
innerHtml is a property of DOM-elements, not a method of jQuery-objects. Use html() instead.
Edit:
Regarding to the comment:
$new_element = $('li').attr('id', refId);
This doesn't create a new <li>-element, it takes the existing <li>-elements inside the document.
To create a new element in jQuery use
$new_element = $('<li/>').attr('id', refId);
It's the same here:
var $link = $('a')
...has to be
var $link = $('<a/>')
Don't mix jQuery and Javascript(DOM)
This is the Javascript(DOM)-way to create an element:
var $new_element = document.createElement('li');
jQuery expects markup for $() while the DOM-method createElement() expects a tagName as parameter .

How can I remove from dom fully upon ajax return?

I trying to remove completely from DOM LI Elements and it's contents including it's checkbox input but haven't been successful.
I have the following function being called after ajax callback, but it removes the contents not the element it self and childs (readyState == 4):
function removepostview(str){
document.getElementById('post'+str).innerHTML = "";
}
Sample LI
<li id="post58">Some Text Here<input type="checkbox" id ="postchk58" value="58" onclick="deletepost(this.value);" /></li>
Please note that no UL is specified in this scenario intentionally. The LI will be normally onto a UL / OL in all other scenarios with proper markup.
It is actually possible doing this without resulting to a js library:)
var e= document.getElementById('post'+str);
e.parentNode.removeChild(e);
There's a remove() method in jQuery for just such a task:
$('#post'+str).remove();
Your tags include jQuery, so why not try this:
$('#post' + str).remove();
Using jQuery:
function removepostview(str){
$('#post'+str).remove();
}
Try this:
var d = document.getElementById('myUL');
var oldLI = document.getElementById('post'+str);
d.removeChild(oldLI);
function removepostview(str){
var postLi = document.getElementById('post'+str);
document.removeChild(postLi);
}

jQuery Remove LI from UL with a hyperlink in the LI

I have a unordered list:
<ul id="sortable">
<li id="1" class="ui-state-default">First x</li>
<li id="2" class="ui-state-default">Second x</li>
<li id="3" class="ui-state-default">Third x</li>
</ul>
I want to remove the <li> from the <ul>. I have handled the click event of the class itemDelete where I try to do a remove but I assume its not working because I can't remove the <li> as a child is calling it?
$('.itemDelete').live("click", function() {
var id = $(this).parent().get(0).id;
$("#" + id).remove();
});
What's the best approach?
Assuming you're using a recent version of jQuery:
$('#sortable').on('click', '.itemDelete', function() {
$(this).closest('li').remove();
});
closest is a little more dynamic than parent (although parent works here as well.) It gets the li that is closest to the current element, upwards in the structure.
Actually, the way you have it as of now, id is going to be undefined, because none of the li's have ids.
why not just do
$(this).parent().remove()
also, don't forget to return false.
You don't have IDs on your <li>s
How about simply
$(this).parent().remove();
What wound up working for me:
Prefix your id attributes with a string or underscore (as others have pointed out)
Since frameworks like jQuery Mobile require that ids be unique across all pages (not just in one page, I prefix with the page name, an underscore, and the numerical id that lets me access records in a database.
Instead of binding to a class or the ul control, use 'on' to bind to the li of the parent list:
$('#sortable').on('dblclick', 'li' function() {
aval = $(this).attr('id').match(/\d+/g); // only want the numbers...
id = aval[0];
name = $(this).text(); // in case you need these for a post...
li = $(this); // so we can remove it from the list after the 'this' object changes inside the ajax call...
// make an ajax call to the server
var jqxhr = $.post( "somepage.php", {name: name, id: id},
function(data) {
li.remove();
$("#sortable").listview("refresh");
},'json').fail(function() { alert("error"); });
return false; // preventDefault doesn't seem to work as well...
});
It could also be looking for the index of the elements with event
$('#sortable').on('click', '.itemDelete', function(e) {
e.preventDefault();
$(e.target.parentElement).parent()[0].remove();
});

Categories