I would like to check that I am not creating a child with a duplicate title. However, I am not sure of the correct way to check and compare. Here's a code example of how the div's children are added:
this.foo = function(inputTitle)
{
var title = inputTitle;
var $ItemContainer = $("#ItemContainer");
$ItemContainer.append('<div class="Item" title="'+title+'"></div>');
// Continue to build the child
var $thisItem = $ItemContainer.children('.Item[title='+title+']');
$thisItem.append('<div class="ItemTitle">'+title+'</div>');
// .....
}
The class will always be Item. How can I check that #ItemContainer does not already have a child with a duplicate title?
The following will tell you if there are any divs with a given title
var exists = $('div[title="' + title + '"]').length > 0;
Related
I'm trying to get the ID of an element by class name like this
var prod_id2 = document.getElementsByClassName('select-selected')[1].id
document.getElementById('hidden-input-2').value = prod_id2;
This works fine, but my issue is that if there's only one element with that class it breaks the functionality, so I need some sort of if statement to only define this var if there is a second div with that class.
Any ideas?
Try this:
const elements = document.querySelectorAll('.test');
if (elements[1]) {
elements[1].innerText = 'Hithere';
}
<div class="test">hi</div>
<div class="test">hi</div>
<div class="test">hi</div>
document.querySelectorAll('.test'); selects all elements with the class test and returns a nodelist.
Then we can access the second element via of the nodelist with elements[1].
Here is how to check for the second element.
You can also set another fallback , different to null:
document.addEventListener("DOMContentLoaded", function(event) {
var selectedElements = document.querySelectorAll('.selected-selected'),
prod_id2 = selectedElements[1] || null;
alert(prod_id2)
});
<div id="test" class="selected-selected"></div>
You can also check that value then:
if (prod_id2) { // do some other stuff with the set value }
It breaks the functionality I think because you are grabbing the 2nd element specifically. You can do:
const prod_id2 = document.querySelectorAll('.select-selected');
and loop over the elements and grab the ID
prod_id2.forEach((prod, index) => {
if(index === 2) {
document.getElementById('hidden-input-2').value = prod.id;
}
})
I am creating a recipe tool that takes a user's input via selected checkboxes. See here: zelda.wptoolkit.us
Part One:
I have a script that will create an array of slugs based off of the selected input values. When a user clicks a checkbox, the associated slug is added to an array called checkedAttr.
<script>
var checkedAttr = [];
$('#wp-advanced-search :checkbox').change(function()
{
checkedAttr = [];
$('#wp-advanced-search :checkbox').each(function(i, item){
if($(item).is(':checked'))
{
checkedAttr.push($(item).val());
}
});
console.log("checkedAttr:", checkedAttr);
});
</script>
Part Two:
I am trying to use the code below to .addClass to any links that contain a slug found in the array from part one.
The link structure: http://zelda.wptoolkit.us/tag/any-crab/
The code:
<script type="text/javascript">
jQuery(function() {
jQuery('#wpas-results-inner > div > div > p > a[href^="/tag/' +
location.pathname.split("/") this.checkedAttr[0] + '"]').addClass('active');
});
</script>
What I am aiming to do is target the links in each card, then add a class to the links whose slug is found in my array. The end goal is to highlight checked 'ingredients' and fade out ingredients that haven't been checked.
I am not exactly sure how to make this function check my array for each slug, I would love to learn what steps are needed to accomplish this!
I am also not certain if my jQuery CSS path is correctly targeting the links
Thanks for any insights!
If you are looking for something like when select particular checkbox, all the card related to that checkbox should be enabled(lets say apply any class active) and once you dis-select the checkbox, we need to remove that particular class from all related checkbox??
you can check the given fiddle.
https://jsfiddle.net/stdeepak22/x1L95dw3/1/
var checkedAttr = [];
$('#checkBoxForCategory :checkbox').change(function()
{
var cardCategory = $(this).val();
var allCards = $('.myCard[card-category=' + cardCategory + ']');
if($(this).is(':checked'))
{
//add the selected category to array
checkedAttr.push(cardCategory);
//add the `active` class for all the card belongs to selected category
$(allCards).each(function()
{
$(this).addClass('active');
});
}
else
{
//remove from array
var index = checkedAttr.indexOf(cardCategory);
checkedAttr.splice(index, 1);
//remove the class for all the card belongs to selected category
$(allCards).each(function()
{
$(this).removeClass('active');
});
}
console.log("checkedAttr:", checkedAttr);
});
Hello I want to get the nodes of class "ms-qSuggest-listItem" from the id.
<div class="ms-qSuggest-list" id="ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList" style="width: 508px;">
<div class="ms-qSuggest-listItem">Everything</div>
<div class="ms-qSuggest-listItem">Videos</div>
<div class="ms-qSuggest-hListItem">People</div>
<div class="ms-qSuggest-listItem">Conversations</div>
</div>
I tried
var nodes = $get("ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList").class(ms-qSuggest-listItem);
If I wanna get the nodes from its direct class - here its working but I want to get it from the ID.
var nodes = $("div.ms-qSuggest-listItem");
Please help.
Thanks.
All the below selectors will give you the matching nodes.
var nodes = $("#ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList").find('.ms-qSuggest-listItem');
OR
var nodes = $("#ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList .ms-qSuggest-listItem");
OR
var nodes = $(".ms-qSuggest-listItem", "#ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList");
Demo: https://jsfiddle.net/tusharj/fr2d9yv1/
You can use the id in conjunction with the class name within the same selector like this:
var long_id = 'ctl00_ctl38_g....';
var nodes = $('#' + long_id + ' .ms-qSuggest-listItem');
Basically what is happening here is the selector is matching the id and then looking inside it's children for the specified class name.
A more explicit way of writing this would be to use the .find() function on the parent node itself.
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
var long_id = 'ctl00_ctl38_g....';
var parent_node = $('#' + long_id);
var children_nodes = parent_node.find('.ms-qSuggest-listItem');
JSFiddle demo
I have HTML like
<a href="/blabla" class="matchupLink">
<span class="teams"> USA</span>
<span class="teams">Brazil</span>
</a>
I want to get the HTML of the elements with class 'teams' within class 'matchupLink'
I tried
$('.matchupLink').each(function (index, obj) {
var teams = $(this).find('.teams');
console.log(teams.html())
});
But that only returns the first instance of the .teams class within each .matchupLink class. So here it only returns USA and not Brazil.
I want to calculate how many characters both teams class have within each matchupLink class. Because then if characterCount >=20, I want to display ellipses.
What should I be doing?
Thanks
You can combine selectors with the classes
$('.matchupLink .teams')
This will return you an array of objects with the class "teams".
UPDATE
Here's a fiddle that prints to the console the length
$('.matchupLink .teams').each(function(index, item){
var $item = $(item);
var teamNameLength = $item.html().length;
console.log($item.html() + ' length is: ' + $item.html().length);
// if ($item.html().length >= 20){
// ::do logic for ellipses::
// }
});
**note the USA prints out a value of 4 because you have a space before in your example.
UPDATE 2
Fiddle alerting the length of both teams
To get the length of both teams, create a variable outside of the loop and increment it appropriately.
var lengthOfBothTeams = 0;
$('.matchupLink .teams').each(function(index, item){
lengthOfBothTeams += $(item).html().length;
});
alert('Length of both team names is: ' + lengthOfBothTeams);
console.log will work on the first match in the set in your example
you should loop over the teams and not the matches
$('.matchupLink .teams').each(function () {
console.log($(this).html())
});
html() only returns the HTML content of the first matched element in the jQuery object. Use each() to iterate over the element and display their HTML content.
$('.matchupLink .teams').each(function (index, obj) {
console.log($(this).html());
});
I have this html code.
<div class="breadcrumb">
Home
<a class="breadcrumb" href="#">About</a>
<a class="breadcrumb" href="#">History</a>
Message from our Founding Members
</div>
Using javascript I want to get the text from the div ".breadcrumb". The problem is the a tag under the div also has a class with the same name, when I run this code:
var names = document.querySelectorAll('.breadcrumb');
return [].map.call(names, function(name) {
return name.textContent;
});
My first element of the array gets the textContent of all the a elements and also the div.
How can I do to get the text of only the div. In this case I want to return only "Message from our Founding Members".
Is there a way to select only the root item of the html, when they have all the same class ?
Thanks
If you want to get the text from the <a> tags with the class="breadcrumb", you can do that by using more specific selectors that include the tag type like this:
var items = document.querySelectorAll("div.breadcrumb a.breadcrumb");
var text = [];
for (var i = 0; i < items.length; i++) {
text.push(items[i].textContent);
}
Working demo: http://jsfiddle.net/jfriend00/kVwH8/
If, what you're trying to do is to get the "Message from our Founding Members" text (I wasn't entirely clear from your original question), then you can do that like this::
var items = document.querySelectorAll("div.breadcrumb a.breadcrumb");
// get node after the last item (that should be the desired text node)
var txtNode = items[items.length - 1].nextSibling;
console.log(txtNode.nodeValue); // Message from our Founding Members
Working demo: http://jsfiddle.net/jfriend00/kynuE/
use div.breadcrumb because that will give you divs with class breadcrumb, not a tags.
You can do this:
var names = document.querySelectorAll('div.breadcrumb')[0].childNodes;
var text = Array.prototype.reduce.call(names,function(prev,node){
if(node.nodeType === 3) return (prev || '' + node.textContent.trim());
});
console.log(text);
There are a lot of ES5 stuff here like trim and reduce so better have those polyfills handy.