How to get PreviousAll element Child class using jquery - javascript

How to get previous all element class list using jquery.
Here is the Example.
<div>
<div>
<span class="one">one</span>
</div>
<div>
<span class="two">one</span>
</div>
<div>
<span class="three">one</span>
</div>
<div id="getclass">getclass</div>
<div>
<span class="four">one</span>
</div>
</div>
I want all the class names above in "getclass" id.
And i'm trying the below things.
var a = $("#getclass").prevAll().find('.class').attr('class');
How can i achive this using jquery.Anyone please Help me to fix this issue.

Your code is looking for elements with the class class.
You can instead get all children of previous siblings and then use the map function to convert this to an array with just class names by returning the className property.
Example:
var a = $("#getclass")
.prevAll()
.children("span")
.get()
.map(function(x) {
return x.className;
});
console.log(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<span class="one">one</span>
</div>
<div>
<span class="two">one</span>
</div>
<div>
<span class="three">one</span>
</div>
<div id="getclass">getclass</div>
<div>
<span class="four">one</span>
</div>
</div>

You can read each element through a loop:
<script type="text/javascript">
$(function () {
var classes = [];
$("#getclass").prevAll().each(function () {
classes.push($(this).find('span').attr('class'));
});
var classNames = classes.join(",");
alert(classNames);
});
classes is an array of class names, you can also get it as a CSV.

Related

Get Element that Parent not a class

I would like to return an element in javascript that does not have a class in its parent element.
For example, I would like to get the child class element in the following code snippet that does not have 'parent' as a class for the parent element:
<div>
<div class= "parent">
<div class="child">
Not to be selected
</div>
</div>
<div>
<div class="child">
To be selected
</div>
</div>
</div>
I tried to return it through xpath in protractor
You can use the :not selector .
console.log(document.querySelectorAll(':not(.parent) > .child'));
<div>
<div class= "parent">
<div class="child">
Not to be selected
</div>
</div>
<div>
<div class="child">
To be selected
</div>
</div>
</div>
There are a few ways to do this. Either you check if the class is there.
var elementList = [];
document.querySelectorAll("div.child").forEach(function(e) {
var parent = e.parentElement;
if(parent.classList == null || !parent.classList.contains("parent")) {
elementList.push(e);
}
})
console.log(elementList);
If the parent class is specific you can use the css :not attribute
var elementList = document.querySelectorAll("div:not(.parent) > div.child");
console.log(elementList);

How to access child of parent in jQuery

Trying to get the child of a parent through a child accessor. Basically trying to get the .block__id through the add__block class.
HTML
<div class="col-12">
<span class="block__id">{{$block->id}}</span>
{{$block->title}}
<span class="add__block">+</span>
</div>
jQuery
$(".add__block").click(function(){
$(this).parent().find(function(){
var id = $(".block__id").text();
});
console.log(id);
});
Currently I get id not defined.
Your logic is almost correct, but the issue is that you're providing a function to find() whereas you simply need to use a selector string:
$(".add__block").click(function() {
var id = $(this).parent().find(".block__id").text();
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12">
<span class="block__id">Block #1</span>
Block title
<span class="add__block">+</span>
</div>
<div class="col-12">
<span class="block__id">Block #2</span>
Block title
<span class="add__block">+</span>
</div>
I'm not very familiar with jQuery, but with vanilla Javascript this is very easy:
const blocks = document.querySelectorAll('.add__block');
for (const block of blocks) {
block.addEventListener('click', (e) => {
console.log(e.target.previousElementSibling.textContent)
})
}
<div class="col-12">
<span class="block__id">{{$block->id}}</span>
{{$block->title}}
<span class="add__block">+</span>
</div>
Another alternative is just looking for the sibling with prev method, which might be slightly faster than going to parent and then search from there.
$('.add__block').click(function(){
var id = $(this).prev('.block__id').text();
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12">
<span class="block__id">Block #1</span>
Block title
<span class="add__block">+</span>
</div>
<div class="col-12">
<span class="block__id">Block #2</span>
Block title
<span class="add__block">+</span>
</div>
Can you try like below:
$(".add__block").click(function(){
var id = $(".block__id").text();
console.log(id);
});
On click you can find the parent of the .add__block element and find the relevant .block__id within the parent as follows,
$(".add__block").click(function(){
console.log($(this).parent().find(".block__id").text(););
});
$('.add_block').prevAll('span')

Unable to retrieve the class name of any parent element fails or returns undefined

Unable to retrieve the class name of any parent element fails or returns undefined:
$(function() {
$(document).on('click','.addfile', function() {
// need to be dinamicaly
var Target = $(this).parents('div').find('[class^="file-plugin-"]');
Target = Target.attr('class');
console.log(Target);
var Target = $(this).closest('div').find('[class^="file-plugin-"]');
Target = Target.attr('class');
console.log(Target);
var Target = $(this).parentsUntil('[class^="file-plugin-"]');
Target = Target.attr('class');
console.log(Target);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap1">
<div class="other class file-plugin-1">
<div class="wrap2">
<div class="input-group-append">
<button type="button" class="remfile">Remove</button>
<button type="button" class="addfile">Add</button>
</div>
</div>
</div>
</div>
i need get: "file-plugin-1" in a var.
You are using class^="
If you look at the documentation, you will see if it is Attribute Starts With Selector [name^=”value”]
That means the attribute needs to be
class="value-abc"
So it is not matching your case because the string is not at the very beginning. You would need to use Attribute Contains Selector [name*=”value”]
The other issue is closest will grab the wrapping div and the div you are looking for is still a grand parent of that div.
$(function() {
$(document).on('click','.addfile', function() {
var elm = $(this).closest('[class*="file-plugin-"]');
console.log(elm.attr("class"));
console.log(elm.attr("class").match(/file-plugin-\d+/)[0])
// how I would do it
var elem = $(this).closest('[data-index]');
console.log(elem.data("index"))
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap1">
<div class="other class file-plugin-1" data-index="1">
<div class="wrap2">
<div class="input-group-append">
<button type="button" class="remfile">Remove</button>
<button type="button" class="addfile">Add</button>
</div>
</div>
</div>
</div>
You can use regex to find elements class starting with certain text
$(document).on('click','.addfile', function() {
var Target = $(this).parents().filter((i, ele)=>ele.className.match(/\bfile-plugin-/)).attr('class')
console.log(Target);
});
The issue is that the class of the div you are after literally does not start with "file-plugin-", it just contains it. You need to examine the class attribute manually, JQuery does not help with this much (that I know of).
Something like this should work:
$(function() {
$(document).on('click','.addfile', function() {
// need to be dinamicaly
var target = $(this).parents("div").filter((_, div) => -1 != div.className.indexOf('file-plugin-'));
// console.log(target[0]);
// Or using the "contains" selector (credit to #epascarello)
target = $(this).parents("div[class*=file-plugin-]");
var string = target.attr("class").split(" ").filter( clazz => clazz.startsWith('file-plugin-'))[0];
console.log(string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap1">
<div class="other class file-plugin-1">
<div class="wrap2">
<div class="input-group-append">
<button type="button" class="remfile">Remove</button>
<button type="button" class="addfile">Add</button>
</div>
</div>
</div>
</div>

How to check if inner <div> has text

what I'm trying to do is to check if my inner <div> has a text for example Ended and then remove if it has a text. I have multiple <div> with the same class name. I tried using .filter(). I would like to remove the div container_one that contains the found element.
Here is my HTML:
var $filstatus = $('.status').filter(function() {
return $(this).text() == 'Ended';
});
$filstatus.remove();
<div class="main_container">
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">On going</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
</div>
Thank you for the help!
I would use the jQuery's selector by content
combined with .closest(). This might be the shortest way:
$('.status:contains("Ended")', $('.main_container')).closest('.container_one').remove();
First ('.status:contains("Ended")') will select all elements that have a class status, contain the text "Ended" and are children of main_container (not needed but is recommended to speed up selection of elements on complex pages).
Then the method .closest('container_one') will climb up the parents tree for each of the elements from the previous step and select the first parent element with class 'container_one'.
At last it will remove all elements found.
Note: all those methods work both with single element and collections of elements, so no need of any for/foreach.
Working JSFiddle Demo
Pure JavaScript solution with forEach:
var div = document.querySelectorAll('.container_one');
div.forEach(function(el){
var target = el.querySelector('.status');
if(target.textContent == 'Ended'){
el.remove();
};
})
<div class="main_container">
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">On going</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
</div>
Try this
$filstatus.parent().parent().remove();
filter will return an array , then use each to loop over that and delete the element. In this case it will remove that specific div but the parent div will still be in dom
var $filstatus = $('.status').filter(function() {
return $(this).text().trim() === 'Ended';
});
$filstatus.each(function(index, elem) {
$(elem).remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main_container">
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">On going</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
</div>
If you want to remove .container_one whose inner child has the text Ended, try
const ended = $('.status').filter((index, element) => $(element).text() === 'Ended')
ended.parents('.container_one').remove()
Since you want to remove the closest ansistor with class .container_one, you will need to use closest
$filstatus.closest(".container_one").remove();
Check this: https://jsfiddle.net/n3d5fwqj/1/
https://api.jquery.com/closest/
Try using this if you don't need $filstatus in other places
$('.status').each(function(){
if ($(this).text() == "Ended"){
$(this).parent().parent().remove();
}
})
I see your problem is you are able to remove the child div status but what you want is to remove the entire parent div with class container_one
you can use $.each for that and use closest(class_name) to remove the parent including its child
$.each($('.status'), function(idx, div) {
if ($(this).text() == 'Ended') {
$(this).closest('.container_one').remove();
}
});
Demo
or you can continue your filter and just add .closest('.container_one') to your jquery selector
var $filstatus = $('.status').filter(function() {
return $(this).text() == 'Ended';
});
$filstatus.closest('.container_one').remove();
Demo

Iterating through data-* elements using JQuery $.children() and $.each()?

I want to be able to iterate through my HTML code and pick every element that harbors the "data-" attribute and collect it's value. I have looked on the web and only found ways to collect data on specific data- elements. I need to get the data-* value without knowing the element name, and so I found the .children() jquery method. However I don't know how to implement it all together.
Here's a quick example of what I'm doing:
HTML:
<div data-example="master">
<div data-example="i">
<div data-example="a">
<span data-example="1"></span>
</div>
<div data-example="b">
<span data-example="2"></span>
</div>
</div>
<div data-example="ii">
<div data-example="c">
<span data-example="3"></span>
</div>
<div data-example="d">
<span data-example="4"></span>
</div>
</div>
</div>
JavaScript:
var master = [];
$("#master").children(function() {
var element = $(this);
var data = element.data('example');
master.push(data);
}
So for this particular example, I want my end-game to have the master array equal [i, a, 1, b, 2, ii, c, 3, d, 4].
But I'm not doing it right because nothing is happening when I trigger the JQuery event.
Use Attribute selector and apply Array.prototype.map over it.
console.log(Array.from($('[data-example]')).map(function(elem) {
return $(elem).data('example');
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-example="master">
<div data-example="i">
<div data-example="a">
<span data-example="1"></span>
</div>
<div data-example="b">
<span data-example="2"></span>
</div>
</div>
<div data-example="ii">
<div data-example="c">
<span data-example="3"></span>
</div>
<div data-example="d">
<span data-example="4"></span>
</div>
</div>
</div>

Categories

Resources