I would like to add a class to an adjacent element using the attribute of an anchor tag with javascript:
HTML:
<ul>
<li><span></span>Black</li>
<li><span></span>Red</li>
<li><span></span>Blue</li>
<li><span></span>Green</li>
<li><span></span>Yellow</li>
</ul>
JS:
$(document).ready(function(){
var swatchColor = $(".swatchButton").data('color');
$(".swatchButton").find('span').addClass(swatchColor);
});
I'm eventually looking for:
<li><span class="blk"></span>Black</li>
Do I need to create some kind of array with forEach()?
Thanks!
http://jsfiddle.net/cL1rpk9L/
use each() in jquery
$(document).ready(function(){
$(".swatchButton").each(function() {
var swatchColor = $(this).data('color');
$(this).find('span').addClass(swatchColor);
});
});
Demo: https://jsfiddle.net/tamilcselvan/cL1rpk9L/3/
Your code var swatchColor = $(".swatchButton").data('color'); will return the data-color of the first element with class swatchButton and $(".swatchButton").find('span').addClass(swatchColor); will assign that value to each span element which is a descendant of an element with class swatchButton.
You need to set the color for each span individually
$('.swatchButton span').addClass(function(){
return this.parentNode.dataset.color;
});
Demo: Fiddle
or
$('.swatchButton span').addClass(function(){
return $(this).parent().data('color');
});
Demo: Fiddle
Related
I have the following HTML structure in my document HTML STRUCTURE
[![enter image description here][1]][1]
I need to grab the info__meta-dates text so only the date using an onClick event in jQuery, this is the code that I have so far:
$("input[type=checkbox]").click(function (e) {
$(this)
.parent()
.parent()
.parent()
.find(".info__meta--dates")
.text()
);
});
But I also get the date text that is within the nested span.
You can clone that span tag and using .remove() remove mdc-typography--caption from the cloned element so that final result will be only the text which you needed
Demo code :
$("input[type=checkbox]").click(function(e) {
var texts = $(this).closest(".ev-info_meta").find(".info__meta--dates").clone(); //clone that span tag
texts.find('span.mdc-typography--caption').remove(); //remove elemnt with class mdc-typography--caption
console.log(texts.text().trim()); //show
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ev-info_meta">
<span class="info__meta--dates"><span class="mdc-typography--caption">dates</span> fffff</span>
<div>
<input type="checkbox">
</div>
</div>
As there is no direct element to get the date, you can try the above method explained by Swati and if you are not willing to remove the element from the DOM then try the string manipulation method.
The below method only works for this scenario.
$("input[type=checkbox]").click(function (e) {
let dateString = $(this).parent()
.parent()
.parent()
.find(".info__meta--dates")
.text()
);
//removing the "date" string from the entire string
let date = dateString.substring(4,dateString.length).trim();
console.log(date);
});
Is there a way to assign nested div attribute with variable? Like
<div>
<div>
123456
</div>
</div>
Become
<div>
<div sectionid="123">
123456
</div>
</div>
BTW above component will be created by JavaScript.
I've tried something like this, but it didn't work.
var a = $('<div><div>123456</div></div>');
a.eq(":nth-child(2)").attr("sectionid", "123");
Try this snippet.
//FOR DOM HTML
console.log("FOR DOM HTML");
//1st way
$('#input > div').find('div').attr("sectionid","123");
console.log($('#input').html());
//2nd way
$('#input > div > div').attr("sectionid","321");
console.log($('#input').html());
//JS HTML
console.log("FOR JS OBJECT");
var input = $('<div><div>123456</div></div>');
//1st way
input.eq(0).children().attr('sectionid', '456');
console.log(input[0].outerHTML);
var input = $('<div><div>123456</div></div>');
//2nd way
$(input[0]).children().attr('sectionid', '789');
console.log(input[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input">
<div>
<div>
123456
</div>
</div>
</div>
nth-child(2) maches elements that are the second child element of their parent. This is not the case for your div, it is the first element of the parent div.
.eq finds an element at a specific index. It is not the place to pass a selector.
The child selector, >, will find a child element, i.e. div>div will find a div that is an immediate child of a div.
Note that the code you've provided, $('<div></div>123456<div></div>');, doesn't create a DOM tree like the one you've pasted.
Update, now that the code is edited, the value of a is a div with a child div. Since a.find will perform a search within a, you don't have to use a child selector, but can find the div immediately:
a.find('div')
Just apply attribute to children. No complicated 'find', eq(), etc.
var a = $('<div><div>123456</div></div>');
a.children().attr('sectionid', '123');
$('body').append(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Why don't you add it in the first place? Not clear if you add it later!
$(document).ready(function() {
var sectionid = "123";
var a = $('<div><div sectionid="' + sectionid + '">123456</div></div>');
$('body').append(a);
});
div[sectionid]{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this - I have added comments to the code to explain what is happening.
Inspect the element to see that the attribute is added
var a = $('<div><div>123456</div></div>'); // change this to match the structure you want
a.children() // .children gets the direct descendant (which should be the nested div
.eq(0) // gets the first in the array that is returned (if there are multiple direct descendents) - it is a 0 based index selector
.attr('sectionid', '123');
$('body').append(a)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
More information about .children()
More information about .eq()
try it :
$(document).ready(function(){
$("div").eq(1).attr("sectionid","123");
})
I have a ul that contain 2 li each of them have a text and a span that contain text like this
<ul>
<li>Erbil<span>text-1</span></li>
<li>Sulymany<span>text-2</span></li>
</ul>
i want to remove Erbil and Sulymany from the code with jquery.... I'm used this in jQuery
$('li').each(function () {
$('li').html($('span'));
});
but the result like this..
text-1text-2text-1text-2
text-1text-2text-1text-2
how to output only a span without repeating?
Try to use .html() and its receiver function to accomplish your task,
$('ul li').html(function(){
return $(this).find('span');
});
DEMO
At its simplest, assuming it's always the first child you want to remove:
$('li').each(function(){
this.removeChild(this.firstChild);
});
JS Fiddle demo.
Is this what you want? Very crude way though.
$('li').each(function () {
var text = $(this).find('span').html();
$(this).html('<span>'+text+'</span>');
});
In the below shown html i have this main div as cxfeeditem feeditem and there are many divs with the same class names and structure.My question is for all the divs starting with the class name cxfeeditem feeditem ,how to get values for the children,
1.with class name cxfeeditem feeditem
2.class=feeditemtimestamp
3.cxcomments feeditemcomments
4.cxfeeditem feeditem
<div class="cxfeeditem feeditem">
<span class="feeditemtext cxfeeditemtext">
This is my blog
</span>
<a class="feeditemtimestamp">Yesterday 2:13PM</a>
<div class="cxcomments feeditemcomments">
These are my comments
</div>
<div class="cxfeeditem1 feeditem1">
My comments for the comment
</div>
</div>
EDIT: Output i want to alert the values like:
This is my blog
Yesterday 2:13PM
These are my comments
My comments for the comment
I tried the following but it returns null:
$("div.cxfeeditem.feeditem").each(function() {
alert($(this).children('span.feeditemtext.cxfeeditemtext').html());
alert($(this).children('a.feeditemtimestamp').html());
alert($(this).children('div.cxcomments.feeditemcomments').html());
alert($(this).children('div.cxfeeditem.feeditem').html());
break;
});
The easiest way I could see is:
$('.cxfeeditem.feeditem').filter(
function(){
return !$(this)
.parents('.cxfeeditem.feeditem')
.length;
}).children().each(
function(){
console.log($(this).text().trim());
});
JS Fiddle demo.
The filter() is used to ensure we're not accessing the elements of the same .cxfeeditem and .feeditem classes that are children of the outer-most element of those classes. This feels a little messy, but given your desired output it seemed the best way.
After that we're simply logging the white-space trim()-ed text() of each of the (direct) child elements that haven't been filtered-out.
Edited in response to question from the OP in comments, below:
What if I want to add a children class name and I do not want to consider all tags; for example if I wanted the value of only a.feeditemtimestamp and span.feeditemtext.cxfeeditemtext
In that case you can either use a second call to filter():
$('.cxfeeditem.feeditem').filter(
function() {
return !$(this).parents('.cxfeeditem.feeditem').length;
}).children().filter(
function() {
var that = $(this);
return that.is('span.feeditemtext.cxfeeditemtext, a.feeditemtimestamp');
}).each(
function() {
console.log($(this).text().trim());
});
JS Fiddle demo.
Or you can use find() (and omit children()):
$('.cxfeeditem.feeditem').filter(
function() {
return !$(this).parents('.cxfeeditem.feeditem').length;
}).find('> span.feeditemtext.cxfeeditemtext, > a.feeditemtimestamp').each(
function() {
console.log($(this).text().trim());
});
JS Fiddle demo.
References:
jQuery:
children().
each().
filter().
find().
parents().
text().
'Plain' JavaScript:
length.
trim().
According to your function
alert($(this).children('span.feeditemtext.cxfeeditemtext').html());
this is giving the text value of span inside the first div whose class is cxfeeditem feeditem
for second div the span is not present so null.
I have some div elements having class name hover, these div elements have parent divs having class name hoverparent but the id's of these parent elements are different.
Is it possible to get the ID of respective .hoverparent element while hovering on my .hover div elements?
I tried to get this by:
$('.hoverparent').attr('id')
But it gives the same first parent id every time.
Structure is like:
<div class="hoverparent" id="hover-1">
<div class="hover">ABC</div>
</div>
<div class="hoverparent" id="hover-2">
<div class="hover">DEF</div>
</div>
You need to use the parent or closest functions to traverse up the DOM tree to find the "parent" element you are looking for:
$(".hover").hover(function() {
var $parent = $(this).closest(".hoverparent");
alert($parent.attr("id"));
});
The difference between parent and closest is that the first will only work if the .hoverparent element is the immediate parent of the .hover element; closest will search upwards through all ancestors to find it.
try $(this).parent().attr('id') , in your hover callback.
$('.hover').mouseover(function() {
$(this).parent().attr('id');
});
don't call your class hover. this should work
$(".hover").hover(
function () {
var id = $(this).parent().attr('id');
});
Add each loop like this :
$(".hoverparent").each(function(){
var id=$(this).attr("id");
alert(id);
});
Use the parent method in the handler for the hover event:
$('.hover').hover(function(evt){
var par = $(this).parent().attr('id');
//Now do with ID what you need
},
function(evt){
//presumably you don't need anything for mouseout
});
You can try the parent() method.
Like this:
$('a').click(function(){
var parentId = $(this).parent('div.hoverparent').attr('id');
});
Try the following:
$('.hover').hover(function() {
var parentID = $(this).parent().attr('id'); alert(parentID);
});
$(".hover").hover(function(){
console.log($(this).closest(".hoverparent").attr("id"));
});
here is the fiddle http://jsfiddle.net/9dJJ9/1/show/