Get list elements and its classes using jquery - javascript

I used $('#ul li').get() to get all the list elements and stored in an array, each of this list elements have classes...
var i;
var listClass = ('#ul li').get();
for(i=0;i<listClass.length;i++){
var theClass = listClass[i].attr("class"); //<--what's the proper function/method/code for this?
var content = listClass[i].innerHTML; //<-- works very well
//other codes here
}
How may i able to get the classes of each list elements...Thanks!

You can use jQuery's own map to do that:
alert($('#ul li').map(function() {
return this.className;
}).get());
http://jsfiddle.net/MhVU7/
for example. You can do anything with the returned array.
The reason the way you're doing it isn't working is because you're calling the non-existent method .attr on a native DOM element - it's not an extended jQuery object.

var lis = document.getElementById("ul").children;
for (var i = 0, len = lis.length; i < len; i++) {
var li = lis[i],
className = li.className,
value = li.value,
text = li.textContent;
// code
}

The get() method returns a native array of DOM elements, not a jQuery object.
You should use jQuery:
var lists = $('ul li');
var className = lists.eq(i).attr('class');
var content = lists.eq(i).text();

If you want to loop through all the elements
$('ul li').each(function(){
var className = $(this).attr('class');
var content = $(this).text();
});

I have commented the code to better help you understand it.
$("#ul li").each(function() { /* you should only be using # selector to identify id's - if it's all ul's you want just put ul. */
var klass = this.className; /* this refers to the native DOM object, which contains className */
var textContents = this.innerText || this.textContent; /* the text of the list, does not include html tags */
var childNodes = this.childNodes; /* the child nodes of the list, each unencased string of text will be converted into a TextNode */
console.log(klass + ' ' + textContents); /* replace console.log with alert if you do not have a console */
console.log(childNodes);
});
here is an example of the above.
Good Luck!

Related

$(selector, element) Native JS alternative

Hi I'm trying to remove all jQuery from my platform one line at a time.
But I'm having some trouble finding a replacement for this
$('[data-attribute="value"]', GenericHTMLElement);
I was hoping it would be something simple like
var div = document.createElement('div');
div.innerHTML = '<div><span data-attribute="value"></span><span data-something-else="1000"></span></div>';
var b = div.childNodes;
var a = b.querySelector('[data-attribute="value"]');
But that's not working either. Does have any suggestions for me?
As commented,
childNodes will give you a list of elements. This list will not have querySelector. If you loop over nodes, you should be able to get it though. But, my suggestion is just do div.querySelector(...)
To be specific, it will be of type NodeList. This is a collection of nodes. So you cannot run querySelector on it. You can either loop over all nodes and do querySelector on them or just so this operation on parent div.
var div = document.createElement('div');
div.innerHTML = '<div><span data-attribute="value">Dummy Text</span><span data-something-else="1000"></span></div>';
var b = div.childNodes;
console.log('Type of childNodes is: ', Object.prototype.toString.call(b))
// getting element using loop over childNodes
for(var i = 0; i<b.length; i++) {
var el = b[i].querySelector('[data-attribute="value"]');
el && console.log(el.textContent)
}
// getting element using parent elenent.
var el1 = div.querySelector('[data-attribute="value"]');
console.log(el1.textContent)
First you need to understand what the first code does. It searches for given selector, limiting it to HTMLElementObject scope. Understanding that we can try to do something similar.
From MSDN example, he is using body element:
var el = document.body.querySelector("style[type='text/css'], style:not([type])");
They have this example with data-attributes, take a look please.
The reason your attempt isn't working is that you're trying to call querySelector on a NodeList, which doesn't have a querySelector method.
If you try it on a single element, it works fine:
function mySelect(selector, el) {
return el.querySelector(selector);
}
var div = document.createElement('div');
div.innerHTML = '<div><span data-attribute="value"></span><span data-something-else="1000"></span></div>';
var b = div.childNodes[0];
console.log(mySelect('[data-attribute="value"]', b));
But this makes it so that mySelect(selector, el) is nothing more than an alias for el.querySelector(selector).
Presumably, you'd want to be able to evaluate a selector on multiple elements at once, and return multiple results, like jQuery does. In that case, you can do so by making some adjustments:
function flatMap(values, f) {
return Array.prototype.concat.apply([], values.map(f));
}
function mySelect(selector, els) {
return flatMap(els.length ? Array.from(els) : [els], function (el) {
return Array.from(el.querySelectorAll(selector));
});
}
var div = document.createElement('div');
div.innerHTML = '<div><span data-attribute="value">span 1</span><span data-something-else="1000"></span></div><div><span data-attribute="value">span 2</span></div>';
console.log(mySelect('[data-attribute="value"]', div.childNodes));
console.log(mySelect('[data-attribute="value"]', div.childNodes[0]));

jQuery selector combination to get to my element

Okay so looking at the image, the highlighted section is the element i need to get too. I need to store the data-id value which is 2391 in the example above.
So starting from the anchor tag with the data-id value of "2392", how do i achieve this.
This is what i have done with no joy.
// This is finding the element, currentID is 2392.
var currentReview = $('.modelLink[data-id="'+ currentID +'"]');
var nextID = currentReview.closest('tr').next().children('td').next().next().next().children('.modalLink').data('id');
How can i achieve this?
Try
var currentReview = $('.modelLink[data-id='+ currentID +']');
var nextID = currentReview.closest('tr').next().find('td a.modalLink').data('id');
Instead of trying to traverse from one deeply-nested anchor to another, just grab all of the IDs into an array and traverse the array--much easier!
// Put all anchor IDs into an array
var ids = [];
$.each("a.modelLink", function( index, value ) {
ids.push(value.attr("data-id"));
});
// Creates: ids[0] = 2391, ids[1] = 2392, etc.
After that, you'll be able to traverse the anchors without worrying about DOM traversal.
// This is finding the element, currentID is 2392.
var currentID = 2392;
var currentReview = $('.modelLink[data-id="'+ currentID +'"]');
// Ensure we do not go out of bounds
current_index = ids.indexOf(currentID);
if(current_index >= 0 && current_index < ids.length - 1) {
nextID = ids[current_index + 1];
}
else {
// Start over from the beginning
nextID = ids[0];
}
// Easily assign the nextReview
nextReview = $('.modelLink[data-id="'+ nextID +'"]');

How to remove duplicate dom elements from body?

I have cloned div duplicate elements in body with the class name "combo". I need to remove all duplicates except the original div element
The problem is that cloned objects will have the same attributes as the original, so it's rather hard to distinguish them, however, you could try this:
(function()
{
//or indeed: querySelector('.combo') which returns a single DOM ref
var original = document.querySelectorAll('.combo')[0];//reference to the original
//clone and add
function removeClones()
{
var i,all = document.querySelectorAll('.combo');
for(i=0;i<all.length;i++)
{
if (all[i] !== original)
{//this is a clone
all[i].parentNode.removeChild(all[i]);
}
}
}
}());
That should do it. An alternative method would be to add a class to the clones, prior to appending them to the DOM:
var clone = original.cloneNode(true);
clone.className += ' combo-clone';
//then, to remove:
var clones = document.querySelectorAll('combo-clone');//selects all clones
var fn = function(originalEl){
var els = document.querySelectorAll('.combo');
for(var i=0; i<els.length; i++){
if( els[i] !== originalEl ){
els[i].parentNode.removeChild(els[i]);
}
}
}
Keep a reference to the cloned elements somewhere (such as an array). Loop over that array and call foo.parentNode.removeChild(foo) on each value.

jquery Getting multiple attributes

Is there a way to get multiple attributes in jQuery
<input type="text" title="hello there" class="maiz"/>
(function() {
var inputTitle = $("input").attr("title","class");
console.log(inputTitle[1])//output:undefined
})();
I'm new to jQuery
You can't get multiple attributes, you just have to call attr again:
var input = $("input");
var title = input.attr("title");
var cls = input.attr("class");
Your example sets the value "class" to the title attribute.
Or more similar to your original code:
var inputTitle = [input.attr("title"), input.attr("class")];
inputTitle[1]; // gives you 'maiz'
You can try this:
for (var i = 0; i < elem.attributes.length; i++) {
var attrib = elem.attributes[i];
if (attrib.specified == true) {
console.log(attrib.name + " = " + attrib.value);
}
}
You can get the attributes using the attributes property on the element object:
var el = document.getElementById("someId");
var attributes = el.attributes; // Here they are
In jQuery you can get the Original element with the get() method, like:
var el = $("input").get(0);
var attributes = el.attributes; // Here they are
Try this:
$('.maiz').click(function(){
for(var i = 0;i < this.attributes.length;i++){
console.log(this.attributes[i]);
}
});
Demo
Jquery selector works pretty much like the CSS selector.
$('selector') if you want to select all elements if a particular class
$('.class') if you want to select class and id
$('.class, #id')
that's basically it. unless you have a specific question

Want to set li innerHTML of ul

I'm writing a javascript function where I get a ul object from my HTML and want to set the text of one of the li elements in theul`. I'm doing:
list = document.getElementById('list_name');
Then I want to access the ith li element of list using a loop.
I have:
for (i = 0; i < 5; i++) {
list[i].innerHTML = "<a>text</a>";
}
but this is not working. What is the proper way to do it?
You need to access the child li elements of the ul. JavaScript and the DOM API can't automagically do that for you.
var list = document.getElementById('list_name'),
items = list.childNodes;
for (var i = 0, length = childNodes.length; i < length; i++)
{
if (items[i].nodeType != 1) {
continue;
}
items[i].innerHTML = "<a>text</a>";
}
You could also use getElementsByTagName('li') but it will get all descendent li elements, and it seems you want only the direct descendants.
You could also avoid innerHTML if you want.
var a = document.createElement('a'),
text = document.createTextNode('text');
a.appendChild(text);
items[i].appendChild(a);
innerHTML can cause issues, such as lost event handlers and the performance issue of serialising and re-parsing the HTML structure. This should be negligible in your example, however.
jQuery Sample code, although the others work:
$("#list_name li").text("<a href=''>text</a>");
Its much more succinct with jQuery
You can try the following
var el = document.createElement("li"),
content = document.createTextNode("My sample text"),
myUl = document.getElementById("ulOne");
el.appendChild(content);
el.id = "bar";
myUl.appendChild(el);
Here's the demo: http://jsfiddle.net/x32j00h5/
I prefer a aproach using getElemenetByTagName, if somehow you get a extra node like a script tag or a span you will have problems. A guess this code will help you:
var list = document.getElementById("mylist");
var items = list.getElementsByTagName("li");
for(var i = 0, size = items.length; i< size; i++){
items[i].innerHTML = "<a href='#'>LINK</a>";
}

Categories

Resources