jquery - select an element with specific content - javascript

I have an html structure like this:
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
...
<div class="test">
<span class="content">100</span>
</div>
In my javascript code, I need to get an <span> element with class content that has exactly 1 or 2 , ..., 100
I tested jquery .contains method, but this returns all elements that have for example 1. such as 1, 12, ....

You can use filter method which accepts a callback function applied to every item.
var array=$('.test').find('.content').filter(function(){
return $(this).text().trim()==100;
});
console.log(Array.from(array));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
<div class="test">
<span class="content">100</span>
</div>

You can proceed in the following manner:
$('.content').each(function(){
if($(this).html() == "2")
{
console.log("THE SPAN WITH 2 IS ");
console.log($(this)[0]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
<div class="test">
<span class="content">100</span>
</div>
What we do here is check through the content class of the spans and check if their inner html is 2 and if it is we console.log it.

You can use the vanilla .indexOf() method.
The indexOf method takes a parameter of the string you want to find and returns either the index (if it's found), or -1 if it's not.
var myEl = document.querySelector(".test"):
for loop...
if( myEl.innerHTML.indexOf(2) != -1 ){
console.log("This element contains the number 2")
}

You can use .filter(), get and check .textContent or .innerHTML of element, at .filter() callback you can use RegExp N$ where N is number to match. For example, to match elements having "1" or "2" set at .textContent you can use RegExp /1$|2$/; to match "100", /100$/; with RegExp.prototype.test()
var filtered = $("span.content").filter((_, {textContent}) =>
/1$|2$/.test(textContent));
filtered.css("color", "green");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
...
<div class="test">
<span class="content">100</span>
</div>

You can do something like this..
$('.test').each(function() {
if($(this).text == '1')
{
var a = $(this).html();
}
});
a will now contain the html of that span which contains your text.

Related

How to add and remove class dynamically to child div based on value in Jquery

if data value is matching with any div inside requestsampler class then dynamically add new class(sampleClass) to test class inside the matching container
js:
var data = **somevalue**;
data is dynamic value
html:
<div class="requestsampler">
<div class= "**somevalue**">
<div class="test"> // add new class <div class="test sample class">
//
</div>
</div>
<div class= "somevalue2">
<div class="test">
//
</div>
</div>
<div class= "somevalue3">
<div class="test">
//
</div>
</div>
</div>
tried not working:
$('.requestsampler').hasClass(data) {
$(.'requestsampler .`${data}` .test').addClass('sampleclass');
}
You could simply use Attribute Contains Prefix Selector [name|="value"] for more info please refer http://jqapi.com/#p=attribute-contains-prefix-selector.. below is the code for your example.
$(document).ready(()=>{
var data = "somevalue"; $('div[class|="'+data+'"]>.test').addClass("sampleclass");
})
.sampleclass{
background-color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="requestsampler">
<div class= "somevalue">
<div class="test"> // add new class <div class="test sample class">
//
</div>
</div>
<div class= "somevalue2">
<div class="test">
//
</div>
</div>
<div class= "somevalue3">
<div class="test">
//
</div>
</div>
</div>
you could try jquery elem.find() api. And also use className with string and numeric combination instead of symbols
i have changed the condition with element find length. Because hasClass() only perform on the selector element. So if you are using find() they will find the matched element.
And also your if condition does not make any sense, without condition is also working same
Updated
If you need first test element. use .eq(0) or else use different className for the first test element
var data = "somevalue";
if ($('.requestsampler').find(`.${data}`).length > 0) {
$('.requestsampler').find(`.${data}`).find('.test').eq(0).addClass('sampleclass');
}
.sampleclass {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="requestsampler">
<div class="somevalue">
<div class="test"> // add new class
<div class="test sample class">
sample
</div>
</div>
<div class="somevalue2">
<div class="test">
//
</div>
</div>
<div class="somevalue3">
<div class="test">
//
</div>
</div>
</div>

map multiple div elements into array

Faced with mapping problem, it returns for me a blank array with two empty elements. Having a button where on click it gets related div block, then I'm trying to get type and number and push them into array. What I am doing wrong here?
<div class="chapter">
<div class="span">
<div class="contact">
<span class="type">
2
</span>
<span class="number">
1111111111
</span>
</div>
<div class="contact">
<span class="type">
4
</span>
<span class="number">
33333333333
</span>
</div>
</div>
</div>
function func(el) {
let block = $(el).closest("div.chapter")
let arr = $(block.find('.contact')).map(function () {
let val = $(this).find('.type, .number').val();
return val;
}).get();
console.log(arr) //result: ["", ""]
}
The .val() method is primarily used to get the values of form elements such as input, select and textarea. You need to use text() method for this, as text() string containing the combined text of matched elements.
Using .val() on span element:
console.log( $('.type').val() )
// Return empty string
console.log( typeof $('.type').val() )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="type">2</span>
Using .text() on span element:
console.log( $('.type').text() )
// Returns '2'
console.log( typeof $('.type').text() )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="type">2</span>
Also call them individually for each element like this:
let arr = block.find('.contact').map(function() {
let type = $(this).find('.type').text().trim();;
let number = $(this).find('.number').text().trim();;
return { type, number};
}).get();
This will return you array of objects, where each object has text content of type & number class elements.
DEMO:
let arr = $('.span').find('.contact').map(function() {
let type = $(this).find('.type').text().trim();
let number = $(this).find('.number').text().trim();
return { type, number};
}).get();
console.log( arr )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="span">
<div class="contact">
<span class="type">
2
</span>
<span class="number">
1111111111
</span>
</div>
<div class="contact">
<span class="type">
4
</span>
<span class="number">
33333333333
</span>
</div>
</div>
Your code does not match with the HTML markup you have provided. You can simply loop through all the element with class contact and find the element inside with specific class to from the object.
Please Note: The span element does not have the value property, you have to use .text().
function func() {
let arr = $('.contact').map(function () {
return {
type: +$(this).find('.type').text().trim(), //find text and convert to number using +
number: +$(this).find('.number').text().trim()//find text and convert to number using +
}
}).get();
console.log(arr);
}
func();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="span">
<div class="contact">
<span class="type">
2
</span>
<span class="number">
1111111111
</span>
</div>
<div class="contact">
<span class="type">
4
</span>
<span class="number">
33333333333
</span>
</div>
</div>
you can use simple JavaScript it's easy!
document.querySelectorAll(".contact").forEach((elm)=>{
arr=[] ;
arr.push(elm.children[0].innerText);
arr.push(elm.children[1].innerText);
console.log(arr)
})

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>

Check for number of html element then run a function

I have three different scenario where the span element presents.
No child span element:
<div class="text" contenteditable="true" id="example">
<div class="outside">Type here</div>
</div>
One child span element:
<div class="text" contenteditable="true" id="example">
<div class="outside">Type here <span class="inside"> please.</span></div>
</div>
Multiple child span element with same class name
<div class="text" contenteditable="true" id="example">
<div class="outside">Type here<span class="inside"> please </span> thanks</div>
<div class="outside">Name <span class="inside"> please.</span> thanks.</div>
</div>
I want to run the following function:
var len = $('span.inside').get(0).nextSibling.length;
console.log(len);
Because the span class can be present once or multiple times, or not at all, I want to check for the presence of the span. Then based on the number of times the span element is there, I would need to run the function for all the span element.
How would I achieve this?
var length = $('span.inside').length;
if (length > 0) {
$('span.inside').each(function() {
var len = $(this).get(0).nextSibling.length;
console.log(len);
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text" contenteditable="true" id="example">
<div class="outside">Type here<span class="inside"> please </span> thanks</div>
<div class="outside">Name <span class="inside"> please.</span> thanks.</div>
</div>
Use class and get length.
For many span use .each() to iterate over
I want to check for the presence of the span.
You can achieve this by checking the length property of the selector:
var $spans = $('span.inside');
var numberOfSpans = $spans.length;
Based on the number of times the span element is there, I would need to run the function for all the span element
This is a simple if statement, then you can use each() to loop over the elements in a selector:
if (numberOfSpans > 5) { // 5 just an example
$spans.each(function() {
// do something with the span here...
});
}

Jquery find and each selector

I am new to jQuery so please help me with the output.
Below is the HTML code used for reference.
<html>
<body>
<div id="level1">
<p>
<span id="level1.1">
<div id="level1.1.1"></div>
<div id="level1.1.2"></div>
</span>
<span id="level1.2">
<div id="level1.2.1"></div>
<div id="level1.2.2"></div>
</span>
<div id="level1.3"></div>
</p>
</div>
</body>
</html>
When I used following as script
<script type="text/javascript">
$(document).ready(function (){
var div = $("#level1").find("div").each(function(){
alert($(this).attr('id'));
});
});
</script>
The result was 5 alerts with id of each div
But when I used
<script type="text/javascript">
$(document).ready(function(){
var div = $("#level1").find("span > div").each(function(){
alert($(this).attr('id'));
});
});
</script>
There were only two alert for level 1.2.1 and 1.2.2
I was wondering why there was no alert for 1.1.1 and 1.1.2 as they also have span as their parents?
Thanks in advance.
If divs can't be child of
then why is
<p>
<div id="level1">
<span id="level1.1">
<div id="level1.1.1"></div>
<div id="level1.1.2"></div>
</span>
<span id="level1.2">
<div id="level1.2.1"></div>
<div id="level1.2.2"></div>
</span>
<div id="level1.3"></div>
</div>
</p>
Working fine ??
Because of your incorrect HTML.
The browser is going to generate your html as followed.
<p>
<span id="level1.1">
</span>
</p>
<div id="level1.1.1"></div>
<div id="level1.1.2"></div>
Because a div can't be a child of a p
If you remove the first <p> in your code, you wil get an alert of the 4 levels sub levels.
divs cannot be children of p in HTML
Change your HTML markup with the following:
<div id="level1">
<span id="level1.1">
<div id="level1.1.1"></div>
<div id="level1.1.2"></div>
</span>
<span id="level1.2">
<div id="level1.2.1"></div>
<div id="level1.2.2"></div>
</span>
<div id="level1.3"></div>
</div>
and you should yield the expected results !
Because your HTML structure is not correct this how your structure is populated :
.find() method only travels a single level down the DOM tree.
Here you can find it.
The .find() and .children() methods are similar, except that the .find() method only travels a single level down the DOM tree.

Categories

Resources