How to get the items inserted in the DOM using DOMNodeInserted - javascript

I want to get the values of items in a Dynamically generated DOM using DOMNodeInserted.
Here is my code.The items #I want to get the values are li eg
<div id="demo">
<ul>
<li class="req">Chemistry</li>
<li class="req">English</li>
<li class="req">Maths</li>
</ul>
</div>
Here is the code
$('#demo').on('DOMNodeInserted', function(e) {
var that = $(this);
if ($(e.target).is('.req')) {
alert(oneoftheitemsintheli);
}
});
I want to get on of the items in the li eg Maths, Chemistry etc. I need to know how to get the items.
Thanks

Given that each li has the class req, you can use each to iterate over them and get the text value - or any other property you need.
$('#demo').on('DOMNodeInserted', function(e) {
$('.req').each(function() {
alert($(this).text());
});
});
Example fiddle

Related

How to find the class of element in a each loop

I am trying to create a menu system where I can change the style of the active page item in the menu. I am using a separate body class on each page, then I want to cycle through the li in the menu and find a match to the body class. At that match I will add the new styling to that menu item.
Here is my code so far.
HTML
<body class="home-state">
...
<div class="menu-left">
<ul>
<li class="home-state">
Home
</li>
<li class="work-state">
Work
</li>
<li class="services-state">
Services
</li>
<li class="about-state">
About
</li>
<li class="blog-state">
Blog
</li>
<li class="shop-state">
Shop
</li>
<li class="contact-state">
<a data-toggle="modal" href="#modal-coworking">Contact</a>
</li>
<li class="project-state">
Project brief
</li>
</ul>
</div>
...
</body>
JS
var bodyClass = $("body").attr('class');
$('.menu-left ul li').each(function(){
First: I want to find the element's class here I have used $(this).attr("class"); which didn't work
var element = $(this);
Second: I want to use a if statement to check to see if the class matches the bodyClass
console.log(element);
Last: If there is a match I want to add the class .active to the element li.
});
Given that elements can have multiple classes, I'd suggesting changing your body element to use a data- attribute rather than a class to specify what the current page is:
<body data-current="home-state">
Then the JS needed to add the active class to the relevant menu item is simple:
$("li." + $("body").attr("data-current")).addClass("active")
You don't need to loop over the menu items comparing classes as mentioned in the question, because you can just directly select the required li element based on its class.
In the event that the body element doesn't have a data-current attribute then $("body").attr("data-current") would return undefined, which would mean the code above tries to select an element with $("li.undefined") and add a class to it. Probably you have no elements with such a class so that would be harmless, but if you wanted to explicitly test that the data-current attribute exists:
var current = $("body").attr("data-current")
if (current) {
$("li." + current).addClass("active")
}
You can do this in couple ways, here is the simple way to do this;
var bodyClass = $("body").attr('class');
$("li." + bodyClass).addClass("active")
You can also use a loop for this one;
var bodyClass = $("body").attr('class');
$(".menu-left li").each(function(i, classes) {
if (bodyClass === $(this).attr("class")) {
$(this).addClass("active")
}
})
both will do the job.
enter image description here
enter image description here
as the comment said,the element can have more than one class ,so you should check it one by one
You missed to bind the click event for the menu item. Follow like below
var bodyClass = $("body").attr('class');
$('.menu-left ul li').on( "click", function() {
var myClass = $(this).attr("class");
alert(myClass);
});
Tested: https://codepen.io/anon/pen/XzYjGY

Checking list item hover states to trigger an action - jQuery

I have 4 images in an unordered list. Ideally I want to be able to load all the list items into an array and do a check to see which one is currently hovered.
I know using the jQuery is() function I can check which is in an :hover state. How would I apply this check to all items within that list array?
<ul class="image-list">
<li class="image-item"><img src="/image1.jpg"/></li>
<li class="image-item"><img src="/image1.jpg"/></li>
<li class="image-item"><img src="/image1.jpg"/></li>
<li class="image-item"><img src="/image1.jpg"/></li>
</ul>
Thanks for any help.
DIM3NSION
Use the mouseover() function:
// Add mouseover event to all your image-items
$('.image-list > .image-item').mouseover(function() {
// $(this) is your hovered image-item object
alert($(this).find('img').attr('src'));
});
Working jsfiddle
Demo: http://jsfiddle.net/GCu2D/758/
JS:
$(function () {
var li = $("ul li"); //get all li. All li are stored in an array.
$(document).on("mouseover", "ul li.image-item", function (e) {
var ele = $(this); //get currently hovered li.
var item = li.index(ele); //get the index of the currently hovered li in that array
console.log(item); //this logs the index. Using this index, do whatever you want with that item.
});
});

Hide <h3> when all ul>li of group does not contain filter term

I've created a small script that filters my ul with a nested ul inside of it. The only issue with my script is I want to hide the title of the nested ul if none of the li's contain the search term, but I am not sure how to go about checking the li's of each "group" as opposed to each li individually. The way it stands, it will display the title if it finds an li in the group matching the search term, but it will immediately turn around and hide the title if the same group contains an li that DOES NOT contain the search term. I know what I'm doing wrong, but I am not as skilled in jquery and cannot seem to visualize how to go about this.
Any help would be great. My code is below:
HTML:
<div id="sitemap">
<h3>Hospital Data Solutions Interactive Site Map</h3>
<hr/>
<p id="header"><input type="text" placeholder="Filter Site Map"> - Use this field filter our list of databases: Search by Topic or Topic Subgroup</p>
<ul id="toplist">
<li class="group">
<h3 class="sTitle">Available Beds - <a style="font-size:18px;">Go to Section</a></h3>
<ul class="sublist">
<li>General</li>
<li>ICU</li>
<li>CCU</li>
<li>BICU</li>
<li>SICU</li>
<li>Other</li>
<li>Hospice</li>
<li>Total</li>
</ul>
</li>
<hr/>
<li class="group">
<h3 class="sTitle">Discharges - <a style="font-size:18px;">Go to Section</a></h3>
<ul class="sublist">
<li>Medicare</li>
<li>Medicaid</li>
<li>Other</li>
<li>Total</li>
</ul>
</li>
</ul>
</div>
Jquery:
$(function(){
$('input[type="text"]').keyup(function(){
var searchText = $(this).val().toLowerCase();
$('.sublist>li').each(function(){
var currentLi = $(this).text().toLowerCase();
if(currentLi.search(searchText) != -1){
$(this).slideDown();
$(this).closest('.group').children('.sTitle').show();
} else { $(this).slideUp(); $(this).closest('.group').children('.sTitle').hide();}
});
});
});
First, select the .sublist elements instead of the lis.
Then iterate that collection using .each(), and use .children() to test each li like you currently are, except use .filter() instead of .each(). This will give you a collection as a result. If the collection is empty, there were no matches. If not, then there was a match.
$('input[type="text"]').keyup(function(){
var searchText = $(this).val().toLowerCase();
$('.sublist').each(function(i, sub){
var matches = $(sub).children().filter(function(i, li) {
return $(li).text().toLowerCase().search(searchText) != -1;
});
if (matches.length) {
$(sub).slideDown().prev().show();
} else {
$(sub).slideUp().prev().hide();
}
});
});
Now the slideDown/Up and show/hide are happening once per sublist instead of on every child li. And I just used .prev() to get back to the h3 element.
If you're going to be hiding those list items that don't match your search you're going to want to deal with them individually anyway, so I wouldn't abandon that approach. So you just need a way to check to see if the term was found somewhere in the search of the nested list. Here's what I might do to utilize what you already have.
After you capture the search term, loop through each of the sublists and set a flag to false; this will be where we capture whether there were any matches. Then loop through that sublist's items, and if you find a match set the flag to true, showing or hiding the item as necessary. Then, after you've checked all the items show or hide the heading based on that flag. It might look something like this:
$('.sublist').each(function(){
found = false;
$(this).children("li").each( function() {
var currentLi = $(this).text().toLowerCase();
if(currentLi.search(searchText) != -1){
$(this).slideDown();
found = true;
} else {
$(this).slideUp();
}
});
if(found) {
$(this).closest('.group').children('.sTitle').show();
} else {
$(this).closest('.group').css("list-style-type", "none");
$(this).closest('.group').children('.sTitle').hide();
}
});
I added a css line to show/hide the header's disc to avoid having that hanging there if everything else disappears. Hope this helps! Let me know if you have any questions.

Get updated order after jQuery Sort

I am using jQuery UI's Sortable to reorder some list items. I would like to update the class of each li based on the updated order after sorting. Here is my html:
<ul id="sortable">
<li class="1">apple</li>
<li class="2">orange</li>
<li class="3">pear</li>
<li class="4">peach</li>
</ul>
What I am trying to achieve is AFTER sorting pear above apple, my classes update like this:
<ul id="sortable">
<li class="1">pear</li>
<li class="2">apple</li>
<li class="3">orange</li>
<li class="4">peach</li>
</ul>
This JSFiddle is close to what I'm after, but I would like to update the class rather than the html: http://jsfiddle.net/4mcpq/3/
As changing the position of one li would change the class of every other li, the only sane way to accomplish this is to iterate over the li elements on the update callback for .sortable:
"update": function (event, ui) {
$(this).children().each(function (i, elem) {
var li = $(elem), // cache lookup
cssClass = elem.className.split(' ').filter(function (name, i, array) {
return /^js[-]\d+$/g.test(name);
}).join(''); // adding .join('') to transform to string
// classes cannot start with a number (see http://www.w3.org/TR/CSS21/grammar.html#scanner).
// using pattern of "js-#" for the custom class
$(elem).removeClass(cssClass).addClass('js-' + i);
});
}
Working demo: http://jsfiddle.net/4mcpq/210/
A caveat: if you have thousands of li elements, this will likely slow your UI. There are much easier (and saner) ways to get the correct target li depending on what you're trying to do.
Why not use something like nth-child() selector in your css.
For example:
#sortable li:nth-child(1) {
/*insert your style for the first child here*/
}
#sortable li:nth-child(2) {
/*insert your style for the second child here*/
}
So I have found I can use .index() to find the updated sort order. Then I can set the class of each li to it's index.
$("#sortable").sortable({
update: function(event, ui) {
$("#sortable li").each(function() {
$(this).removeClass();
var $index = $(this).index();
$(this).prop("class", $index);
});
}
});
See this Fiddle: http://jsfiddle.net/2f9vkhxj/8/

Cant get the value of <li data-*> element. Tried Javascript as well as Jquery

The following is my dropdown list.
<ul id="navBar" data-value="">
<li data-city-value="blore">Bangalore
<ul>
<li data-city-value="delhi">Delhi</li>
<li data-city-value="che">Chennai</li>
<li data-city-value="jaipur">Jaipur</li>
<li data-city-value="hyd">Hyderabad</li>
<li data-city-value="mum">Mumbai</li>
<li data-city-value="pune">Pune</li>
</ul>
</li>
</ul>
And the following are my methods I tried to access the data-city-value attribute.
Method 1)
var cityName = document.getElementById('navBar');
var city = cityName.getAttribute('data-city-value');
alert(city);
It alerts "null"
Method 2)
var cityName = document.getElementById('navBar');
var city = cityName.dataset.cityValue;
alert(city);
It alerts "undefined".
Method 3)
$('#navBar li').click(function() {
$(this).parent().data('value', $(this).data('cityValue'));
});
alert($('#city').data('value'));
It alerts "undefined".
I checked the syntax to get data value here
It would be of great help if you can help me find where I am doing mistake.
Thanks. :)
IN your first two methods you target the top ul with id navBar. In the third method you do $(this).parent() which again takes you to the ul element.
That element does not have the data-city-value attribute.
The jquery method should be
$('#navBar').on('click','li', function(e) {
var city = $(this).data('city-value');
alert(city);
return false;
});
Demo at http://jsfiddle.net/gaby/Mb7KS/
As pointed out by Gaby, you need to reach the element firts. Try this:
$('#navBar:first-child')
This is how you can iterate through your data-city-value attributes:
$('li[data-city-value]').each(function(index,element){
alert($(element).data('city-value'));
});
You can also check my jsFiddle example.
For click events:
$(document).ready(function()
{
$('li').click(function() {
alert($(this).data('city-value'));
return false;
});
});
You should return false because the top li element has inner elements and it was triggering inner li element click event.
My second jsFiddle demo.

Categories

Resources