How to select element by data-date attribute with jQuery? - javascript

I've tried to create a code snippet for an example of a selector I was trying to use and it's not working. Can someone eyeball it and tell me what I have wrong?
var dateDiv = null;
var expenseDate = "06/22/2016";
$(":data(date)").each(function() {
var element = $(this);
element.css("backgroundColor", element.data("color"));
});
.expense-item {
margin-left: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="contentWrapper">
<div data-date="06/22/2016" data-color="red">
06/22/2016
<div class="expense-body">
<div class="expense-item">
<p>
This is an expense (1)
</p>
</div>
<div class="expense-item">
<p>
This is an expense (2)
</p>
</div>
<div class="expense-item">
<p>
This is an expense (3)
</p>
</div>
</div>
</div>
<div data-expense-date="06/23/2016" data-color="blue">
<div class="expense-body">
06/23/2016
<div class="expense-item">
<p>
This is an expense (1)
</p>
</div>
<div class="expense-item">
<p>
This is an expense (2)
</p>
</div>
</div>
</div>
<div data-expense-date="06/24/2016" data-color="yellow">
<div class="expense-body">
06/24/2016
<div class="expense-item">
<p>
This is an expense (1)
</p>
</div>
<div class="expense-item">
<p>
This is an expense (2)
</p>
</div>
<div class="expense-item">
<p>
This is an expense (3)
</p>
</div>
<div class="expense-item">
<p>
This is an expense (4)
</p>
</div>
</div>
</div>
</div>
My code was inspired by this example:
http://api.jqueryui.com/data-selector/

You want an attribute selector:
$("[data-date]")
Fiddle: https://jsfiddle.net/j3cmo4ow/5/
If you want the :data pseudo selector to work, you need to include jQuery UI.

$("[data-color]").each(function() {
var element = $(this);
element.css("backgroundColor", element.attr('data-color'));
});
Fiddle: https://jsfiddle.net/j3cmo4ow/8/

Your issue with selector $(":data(date)")
you can select all elements with date Data using this selector : $("*[data-date]")
var dateDiv = null;
var expenseDate = "06/22/2016";
$("*[data-date]").each(function() {
var element = $(this);
element.css("background-color", element.attr('data-color'));
});
var dateDiv = null;
var expenseDate = "06/22/2016";
$("*[data-date]").each(function() {
var element = $(this);
element.css("backgroundColor", element.data("color")); // Also works if you want.
});
.expense-item {
margin-left: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="contentWrapper">
<div data-date="06/22/2016" data-color="red">
06/22/2016
<div class="expense-body">
<div class="expense-item">
<p>
This is an expense (1)
</p>
</div>
<div class="expense-item">
<p>
This is an expense (2)
</p>
</div>
<div class="expense-item">
<p>
This is an expense (3)
</p>
</div>
</div>
</div>
<div data-expense-date="06/23/2016" data-color="blue">
<div class="expense-body">
06/23/2016
<div class="expense-item">
<p>
This is an expense (1)
</p>
</div>
<div class="expense-item">
<p>
This is an expense (2)
</p>
</div>
</div>
</div>
<div data-expense-date="06/24/2016" data-color="yellow">
<div class="expense-body">
06/24/2016
<div class="expense-item">
<p>
This is an expense (1)
</p>
</div>
<div class="expense-item">
<p>
This is an expense (2)
</p>
</div>
<div class="expense-item">
<p>
This is an expense (3)
</p>
</div>
<div class="expense-item">
<p>
This is an expense (4)
</p>
</div>
</div>
</div>
</div>

This fails, because the jQueryUI library is invoked over http, while the fiddle itself is loaded via https.
Therefore the script is considered as insecure.
When you run your fiddle with the console open you see the following error:
Mixed Content: The page at 'https://jsfiddle.net/j3cmo4ow/4/' was loaded over HTTPS, but requested an insecure script 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js'. This request has been blocked; the content must be served over HTTPS.

The :data() selector does not work based off of HTML attributes with the prefix data-.
Instead, it matches and elements that have data stored via the jQuery function .data( "foo", value ).

Note, that the :data() selector is part of jQuery UI, and not part of the core jQuery library, so unless you include jQuery UI, that selector is not expected to work.

Related

jquery wont set image src from another image

I have started some blogs using Weebly now I want to do several changes to the blog UI, everything went well until I wanted to do this. I wanted to get the image path from the image inside blog-content and set it on the blog-post-image. In my head, this jquery looks logical, but somewhere error lays.
Few things to care about, I should use each because there are many of the blog posts and I cannot use ids because of the same reason, cannot use the same id multiple times.
HTML:
$('.blog-post-image').each(function() {
var $me = $(this);
var blogPostImage = $me.siblings('.blog-content').children('img').attr('src');
$me.attr('src', blogPostImage);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blog-post-746510653886732592" class="blog-post">
<div class="blog-header">
<div class="blog-post-container">
<h2 class="blog-title">
</h2>
<p class="blog-date">
<span class="date-text">
15/6/2021
</span>
</p>
<div>
<img class="blog-post-image" />
</div>
</div>
</div>
<div class="blog-content">
<div>
<div class="wsite-image wsite-image-border-none " style="padding-top:10px;padding-bottom:10px;margin-left:0;margin-right:0;text-align:center">
<a>
<img src="/uploads/7/7/9/0/77909082/820610853.jpg" alt="Picture" style="width:100%;max-width:1100px">
</a>
<div style="display:block;font-size:90%">
</div>
</div>
</div>
.blog-post-image doesn't have any siblings. Siblings are immediate children of the same parent element, but there are no other elements in the div containing <img class="blog-post-image" />.
You need to go up to the .blog-header to get its sibling.
Also, instead of using .each(), you can use a function in .attr(). It automatically loops, and assigns the return value to the attribute.
$('.blog-post-image').attr('src', function() {
return $(this).closest('.blog-header').siblings('.blog-content').find('img').attr('src');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blog-post-746510653886732592" class="blog-post">
<div class="blog-header">
<div class="blog-post-container">
<h2 class="blog-title">
</h2>
<p class="blog-date">
<span class="date-text">
15/6/2021
</span>
</p>
<div>
<img class="blog-post-image" />
</div>
</div>
</div>
<div class="blog-content">
<div>
<div class="wsite-image wsite-image-border-none " style="padding-top:10px;padding-bottom:10px;margin-left:0;margin-right:0;text-align:center">
<a>
<img src="/uploads/7/7/9/0/77909082/820610853.jpg" alt="Picture" style="width:100%;max-width:1100px">
</a>
<div style="display:block;font-size:90%">
</div>
</div>
</div>
Two things:
1.) .blog-content is not a sibling of .blog-post-image
2.) .children() only looks one level deep to find the element you are looking for.
What you need to do is traverse upwards to find a sibling of .blog-content and then use the .find() function to do a deep search of the given DOM node to find what you're looking for.
$('.blog-post-image').each(function() {
var me = $(this);
var blogPostImage = me.parent().parent().parent().siblings('.blog-content').find('img').attr('src');
me.attr('src', blogPostImage);
});
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="blog-post-746510653886732592" class="blog-post">
<div class="blog-header">
<div class="blog-post-container">
<h2 class="blog-title">
</h2>
<p class="blog-date">
<span class="date-text">15/6/2021</span>
</p>
<div>
<img class="blog-post-image" />
</div>
</div>
</div>
<div class="blog-content">
<div>
<div class="wsite-image wsite-image-border-none " style="padding-top:10px;padding-bottom:10px;margin-left:0;margin-right:0;text-align:center">
<a>
<img src="/uploads/7/7/9/0/77909082/820610853.jpg" alt="Picture" style="width:100%;max-width:1100px">
</a>
<div style="display:block;font-size:90%">
</div>
</div>
</div>
</div>
</div>
</body>

HTML JavaScript querySelector to find an element whose child has a specific data attribute

In my below HTML markup, I'd like to query the <div> that has a data-parent set to "true", and the contained child has data-child-gender set to "true" and inner html is "male".
<div id="grandparent">
<div id="parent1" data-parent="true">
<div id="child1" data-child-gender="false">
male
</div>
</div>
<div id="parent2" data-parent="true">
<div id="child2" data-child-gender="true">
female
</div>
</div>
<div id="parent3" data-parent="false">
<div id="child3" data-child-gender="true">
female
</div>
</div>
<div id="parent4" data-parent="true">
<div id="child4" data-child-gender="true">
male
</div>
</div>
</div>
Given the above scenario, the expected <div> is parent4.
What is the JavaScript querySelector to use?
First use querySelectorAll which will give an array. Then iterate over it and check and get element with required data attribute.
After that you can use use a if & check the content inside it
let k = document.querySelectorAll('[ data-parent=true]').forEach(function(item) {
let elem = item.querySelector('[data-child-gender=true]');
if (elem !== null && elem.innerHTML.trim() === 'male') {
console.log(item.id)
}
})
<div id="grandparent">
<div id="parent1" data-parent="true">
<div id="child1" data-child-gender="false">
male
</div>
</div>
<div id="parent2" data-parent="true">
<div id="child2" data-child-gender="true">
female
</div>
</div>
<div id="parent3" data-parent="false">
<div id="child3" data-child-gender="true">
female
</div>
</div>
<div id="parent4" data-parent="true">
<div id="child4" data-child-gender="true">
male
</div>
</div>
</div>
There isn't one querySelector you can use for this (as you can't use it to select specific text within elements). However, you can use .querySelector() with .filter() to get more specific results:
const true_children = [...document.querySelectorAll("[data-parent='true'] [data-child-gender='true']")];
const res = true_children.filter(({innerHTML:g}) => g.trim() === "male");
console.log(res);
<div id="grandparent">
<div id="parent1" data-parent="true">
<div id="child1" data-child-gender="false">
male
</div>
</div>
<div id="parent2" data-parent="true">
<div id="child2" data-child-gender="true">
female
</div>
</div>
<div id="parent3" data-parent="false">
<div id="child3" data-child-gender="true">
female
</div>
</div>
<div id="parent4" data-parent="true">
<div id="child4" data-child-gender="true">
male
</div>
</div>
</div>
The problem that the question describes, cannot be solved using query-selectors alone. This is because of following reasons:
The query selectors always works on descendants, so while evaluating that the child div has data-child-gender="true", there will be no way to return the parent element. The query-selector will return the child div.
There is no way to evaluate the inner text or contained text of an element in query-selector.
These two limitations can be worked around by using JavaScript, provided that you were going to use the query-selector in JS.
Something like the following snippet should work.
document.querySelectorAll('div[data-parent=true] div[data-child-gender=true]')
.filter(function(elem) {
return elem.innerText === 'male'; // filter the elements containing male string.
})[0].parentElement; // return the parent of matched element.
An equivalent logic could be derived for selenium too. Otherwise if this much logic is unacceptable, you can always use the much richer xpath selectors. xpath wouldn't have either of the limitations mentioned above.

jQuery ID matching

This Toggle on a mouseover event works fine:
jQuery(document).ready(function(){
jQuery(".info").hide();
jQuery(".trigger").mouseout(function(){
jQuery(".info").slideUp(200);
});
jQuery(".trigger").mouseover(function(){
jQuery(".info").slideToggle();
});
});
but have too many objects so if i trigger some trigger, it shows me all areas with the info class. The easiest way would be adding an ID :
<div class="trigger" id="1">Details</div>
<div class=" info" id="1">
<p> <b> Projektbeschreibung </b> </p>
<p> Lorem ipsum one. </p>
</div>
<div class="trigger" id="2">Details</div>
<div class=" info" id="2">
<p> <b> Projektbeschreibung </b> </p>
<p> Lorem ipsum two. </p>
</div>
So the trigger is only triggering the info to witch its belongs.
I'm not very into jQuery, so my question is how do I get this id matching the js code?
Inside the callbacks, refer to the object called with this:
jQuery(document).ready(function(){
jQuery(".info").hide();
jQuery(".trigger").mouseout(function(){
jQuery(this).slideUp(200);
});
jQuery(".trigger").mouseover(function(){
jQuery(this).slideToggle();
});
});
Use this in handler function which refers to Element over which event is invoked!
jQueryObject.next([SELECTOR]) will select immediate sibling element of the current element.
Note: Remove Duplicate IDs from document as, There must not be multiple elements in a document that have the same id value.
jQuery(document).ready(function() {
jQuery(".info").hide();
jQuery(".trigger").mouseout(function() {
jQuery(this).next(".info").slideUp(200);
});
jQuery(".trigger").mouseover(function() {
jQuery(this).next(".info").slideDown(200);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="trigger">Details</div>
<div class=" info">
<p> <b> Projektbeschreibung </b>
</p>
<p>Lorem ipsum one.</p>
</div>
<div class="trigger">Details</div>
<div class=" info">
<p> <b> Projektbeschreibung </b>
</p>
<p>Lorem ipsum two.</p>
</div>
jQuery(document).ready(function(){
jQuery(".trigger").hover(function() {
$('#' + $(this).attr('data-target')).stop(true).slideToggle();
});
});
.info {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="trigger" data-target="item-1">Details</div>
<div class=" info" id="item-1"><p> <b> Projektbeschreibung </b> </p>
<p> Lorem ipsum one. </p>
</div>
<div class="trigger" data-target="item-2">Details</div>
<div class=" info" id="item-2"><p> <b> Projektbeschreibung </b> </p>
<p> Lorem ipsum two. </p>
</div>
#Jonathan it's easy to do with JQuery.
in your JQuery function you just need make some tweaks to get the ID and perform the function as expected.
jQuery(document).ready(function(){
jQuery(".info").hide();
jQuery(".trigger").mouseout(function(){
var elem_id = $(this).attr('id');
jQuery(".info#"+elem_id).slideUp(200);
});
jQuery(".trigger").mouseover(function(){
var elem_id = $(this).attr('id');
jQuery(".info#"+elem_id").slideToggle();
});
});
Try above code.

Remove all classes which contain following style

how do I remove all classes which contain the following style?
HTML
<div class="viewed" style="background:#F9F0D5">
<div class="left">
<span class="title">My </span>
<p>MPA </p>
</div>
<div class="right">
<span>5</span>
</div>
</div>
code sample
document.getElementsByClassName('viewed')[0].style.background:#F9F0D5)[0].remove();
Javascript solution Demo Fiddle :
var viewed = document.querySelectorAll('.viewed[style="background:#F9F0D5"]');
for(i=0;i<viewed.length;i++){
viewed[i].classList.remove('viewed');
}
You have tagged jQuery, so using jQuery selectors,
$('.viewed[style="background:#F9F0D5"]').removeClass('viewed');
To remove the element,
$('.viewed[style="background:#F9F0D5"]').remove();
Hi refere this https://plnkr.co/edit/FxemUZMAmEqo2oXvvMXN?p=preview
$(".viewed[style='background:#F9F0D5']").remove();
this is the syntax
$('div[style*=block]').removeAttr('style');
Have a look attached snippet.
$(".viewed").each(function() {
var finalres=$(this).attr('style');
$(this).removeClass('viewed');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="viewed" style="background:#F9F0D5">
<div class="left">
<span class="title">My </span>
<p>MPA</p>
</div>
<div class="right">
<span>5</span>
</div>
</div>
<div class="viewed" style="background:#F9F0D6">
<div class="left">
<span class="title">My </span>
<p>MPA</p>
</div>
<div class="right">
<span>5</span>
</div>
</div>
May be this is what you are looking for?
$("*[style*='backlground:#F9F0D5']").removeClass()
Initial * can be replaced by specific selector.
but if you want to remove all the classes for the element containing the style the use or else for your example 2 options are there
1)
$("div[style*='backlground:#F9F0D5']").removeClass()
2)
$(".viewed[style*='backlground:#F9F0D5']").removeClass()
I hope this helps you

jQuery Traversal -- Find an Element Relative to Common Ancestor

I frequently find I'm needing to select an element that is nearby, typically within a common container, but which is not a sibling or within the same "tree line". For example, given this HTML:
<div id="container-left" class="container">
<div class="sidebar">
<button class="more-link">Show Extras</button>
</div>
<div class="content">
<div class="tidbits">
<p>Lorem ipsum beep bop boop</p>
<p class="extra hidden">Exxtra info about lorem ipsum!</p>
</div>
</div>
</div>
<div id="container-right" class="container">
<div class="sidebar">
<button class="more-link">Show Extras</button>
</div>
<div class="content">
<div class="tidbits">
<p>Lorem ipsum beep bop boop</p>
<p class="extra hidden">Exxtra info about lorem ipsum!</p>
</div>
</div>
</div>
What I'll do is attach an event listener to the "Show Extras" buttons, which target the p tags with class of extra, and on click, toggle the hidden class. So (using jQuery) I typically select like this:
$(".more-link").on("click",function(){
var $this = $(this);
var $extraElement = $this.closest(".container").find(".extra");
$extraElement.toggleClass("hidden");
});
My question: is there a better way to select the extra element than the .closest().find() combo? Something about it just feels a little clunky.
well.. you could navigate to sidebar siblings and find extra... but the mess would be similar...
Other way to do it is to generate a HTML5 data attribute at button:
<button class="more-link" data-extra='#some-generated-extra-id'>Show Extras</button>
...
<p id='some-generated-extra-id' class="extra hidden">Exxtra info about lorem ipsum!</p>
your code:
$(".more-link").on("click",function() {
var $extraElement = $($(this).data('extra'));
$extraElement.toggleClass("hidden");
});

Categories

Resources