Check for number of html element then run a function - javascript

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...
});
}

Related

jquery - select an element with specific content

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.

Remove / (slash) from dom using jquery/javascript

I have dom structure like
<div class="container">
<span> test1 </span>
/
<span> test2 </span>
/
<span> test3 </span>
</div>
which produces output like
test1/test2/test3
i am able to remove the span .. but not able to remove the slash from dom.. can any one please help me to remove the slash from dom so i can get output like
test1test2test3
You can get all .contents() of the element including Node.TEXT_NODE afterwards .filter() can be used to get text nodes then use .remove().
$('.container').contents().filter(function() {
return this.nodeType == Node.TEXT_NODE
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<span>test1</span> /
<span>test2</span> /
<span>test3</span>
</div>
You can iteratate .childNodes of parent .container element, check if .textContent of current node contains "/", if true call .parentElement.removeChild with current node as parameter.
var container = document.querySelector(".container");
for (let node of container.childNodes) {
if (node.textContent.indexOf("/") > -1) {
node.parentElement.removeChild(node)
}
}
<div class="container">
<span> test1 </span> /
<span> test2 </span> /
<span> test3 </span>
</div>
You can make use of children() function and edit the container HTML.
var $container = $('.container');
$container.html($container.children());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<span>test1</span>
/
<span>test2</span>
/
<span>test3</span>
</div>

find children while moving upwards in dom

This can be sound little confusing but here it is.
What i want is to find the children(OF CLASS PARENT ) when user clicks on class target.
Important: I am not aware of children class & child inside html structure.Target class can be after 'blah' like in first case OR can be directly after children like in second case.
Information available: class "PARENt" and $(this) [class target]
Find: Children(ID) of class PARENT (you cannot use class .children)
<div class="parent">
<div class="children" id="1">
<div class="blah">
<div class="target">TARGET</div>
</div>
</div>
<div class="children" id="2">
<div class="target">TARGET</div>
</div>
<div class="children" id="3">
<div class="blah">
<div class="target">TARGET</div>
</div>
</div>
Example:
Clicking Target 1 would produce: ID = 1
Clicking Target 2 would produce: ID = 2
Clicking Target 3 would produce: ID = 3
If you want to find only ONE ID use:
$('.target').click(function() {
var found = false;
var parent;
var previous;
while(!found) {
if (previous) {
parent = previous.parent();
} else {
parent = $(this).parent();
}
if (parent.hasClass('parent')) {
found = previous;
}
previous = parent;
}
console.log(found.attr('id'));
});
Demo.
To literally answer your question:
$(".parent *") will give you ALL of the children of .parent no matter how many layers deep
To practically answer your question:
Limit possible elements, classes, IDs, etc.
$(".parent div, .parent span, .parent .child ...etc")
You can also grab only the immediate children of an element or set of elements by using the > CSS selector:
$(".parent > *") for example, will give you ALL of the immediate children of .parent
In the context of your problem
$(".target").on("click", function () {
$(this).closest(".parent").children();
// OR
$(this).closest(".parent").find("*");
});
To get the specific ID Given your current DOM structure...
$(".target").on("click", function () {
var id = $(this).closest("[id]").attr("id");
console.log(id);
});
Use .parentsUntil() to get the set of all parents up to (but not including) .parent. Then get the last element of this to get the child of the parent.
$(".target").click(function() {
var child = $(this).parentsUntil(".parent").last();
console.log(child.attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parent">
<div class="children" id="1">
<div class="blah">
<div class="target">TARGET</div>
</div>
</div>
<div class="children" id="2">
<div class="target">TARGET</div>
</div>
<div class="children" id="3">
<div class="blah">
<div class="target">TARGET</div>
</div>
</div>
</div>
Another

jQuery Insert closing div tag and opeing div tag after count

I am trying to get jquery to close a div and inset an opening div with a class after x amount of items.
Here is what I have tried:
$(this).after('</div> <div class=\"bar">Bar');
it outputs:
<div class="bar">Bar</div>
What I need is:
<div class="item2">
<div class="CountThese2"> Count Me </div>
<div class="CountThese2"> Count Me </div>
</div>
<div class="bar">
<div class="CountThese2"> Count Me </div>
<div class="CountThese2"> Count Me </div>
</div>
<div class="bar">
<div class="CountThese2"> Count Me </div>
<div class="CountThese2"> Count Me </div>
</div>
<div class="bar">
<div class="CountThese2"> Count Me </div>
<div class="CountThese2"> Count Me </div>
</div>
http://jsfiddle.net/yoderman94/JEtj2/
You can't add half a tag. I think what you're trying to do is wrap the elements. Your fiddle is pretty messy, but here's a simple example of how you can do that:
http://jsfiddle.net/9Q62H/
while($('#wrapper > a:lt(2)').wrapAll('<div class="bar">bar</div>').length) { }
Which turns this:
<div id="wrapper">
1
1
1
1
1
1
1
1
</div>
into this:
<div id="wrapper">
<div class="bar">bar
1
1
</div>
<div class="bar">bar
1
1
</div>
<div class="bar">bar
1
1
</div>
<div class="bar">bar
1
1
</div>
</div>
You can't manipulate the DOM that way, with or without jQuery. To accomplish the same thing, insert a new div after the current div's parent, and then move all of the current div's following siblings to the new div:
var bar = $("<div>").addClass("bar").text("Bar");
bar.insertAfter($(this).parent());
bar.append($(this).nextAll());
Edit: To preserve text nodes, including the whitespace between your links, it's not quite as simple as $(this).nextAll(), sadly. You need to use .contents() to select the text nodes, then slice at the index of this:
var contents = $(this).parent().contents();
var bar = $("<div>").addClass("bar").text("Bar");
bar.insertAfter($(this).parent());
bar.append(contents.slice(contents.index(this) + 1));
http://jsfiddle.net/JEtj2/6/
I'm going to recommend a different approach here. When you call .after() you need to be giving it a complete open and close tag. You cannot open a tag then close it later like you are trying to above.
My advice would be to try and take an approach like the following, so you can pass a complete open and close tag to .after()
var theDiv = "<div class='bar'>";
for(var i = 0; i < 2; i++) {
theDiv += '<div class="CountThese2"> Count Me </div>';
}
theDiv += "</div>";
$('#thing').after(theDiv);
See how I constructed the whole div including contents before calling .after() ?

selecting span value inside div

Let's say I have
<div id="1">
<span id="name">Josh</span>
<div id="quote">Run</div>
</div>
<div id="2">
<span id="name">Mark</span>
<div id="quote">Run</div>
</div>
How would I select the name between the span tags from the first div?
$("#quote").click(function(){
var name = $('#name').html();
});
Firstly, id's have to be unique in an html document. So,ideally, you need to change those id's within the div to a class. Secondly, id's cannot begin with a numeric, so you need to change your div id's to start with a letter or underscore.
With that in mind, given this structure:
<div id="one">
<span class="name">Josh</span>
<div class="quote">Run</div>
</div>
<div id="two">
<span class="name">Mark</span>
<div class="quote">Run</div>
</div>
you would be looking for:
$("#quote").click(function(){
var name = $('#one .name').html();
});
id's should be unique across a page. You should change the name and quote id's to a class, which do not have to be unique.
<div id="1">
<span class="name">Josh</span>
<div class="quote">Run</div>
</div>
<div id="2">
<span class="name">Mark</span>
<div class="quote">Run</div>
</div>
You could then select via:
$('#1 .name')
You should also bare in mind that id's should not start with a number (except in HTML5)
var name = $("#1 span").html()
or
var name = $('#1 #name').html();
this should work for you:
$("#1 span").text();
You have some problems with your HTML though. You should not have any duplicate IDs in your HTML, they must be unique. ID shouldn't start with a number either.
You can view the fiddle here: http://jsfiddle.net/
you can select the first span tag content of your div #1 this way as well :
var name = $("#1 span:first").html();
Adding #1 before #name would select the first div
$("#quote").click(function(){
var name = $('#1 #name').html();
});

Categories

Resources