I have the following code:
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<span></span>
<div class="content" id="2">
<div class="reply"></div>
</div>
<div class="content" id="1">
</div>
<div class="content" id="3">
<div class"reply"></div>
</div>
<script>
var n = $( ".reply" ).length;
$( "span" ).text( "There are " + n + " divs.");
</script>
</body>
</html>
I am trying to write a jQuery script that will check individual divs with unique id's to see if it contains the "reply" div. I have code to see if the "reply" div exists at all working. I am new to jQuery so I am unsure how to go about this.
var n = $( ".reply" ).length;
$( "span" ).text( "There are " + n + " divs.");
Use #uniqueId .reply jQuery selector:
alert("The id with id '3' contains" + $("#3 .reply").length + ".reply divs.");
To check if a particular Id containing .reply div:
if($("#id .reply").length>0)
{
//reply exist in this id
}
Above code works like this
$("#id .reply").length
returns the occurrence of .reply in #id selector.
If present then return 1 else return 0.
You are on correct path, if you want to check for unique id use #elementId
if($("#ID .reply").length > 0)
{
//div exists
}
Related
I'm using a search function to highlight text (function 2) in different chapters. In parallel most of this text is stored in div called content to ease reading. You can toggle these div to read the text (function 1).
When text is found by function 2, it's no longer possible to toggle the text in this chapter. I suppose this is related to use of "this" in function 1 (If I delete this it works) or handlers (if I add live in front of click in function 1 it works but live is deprecated and remplacement "on" is not working).
// function 1 : toggle content when clicking the button
$(".chapter button").on('click',function(f) { //live deprecated to be replaced
f.preventDefault();
var id = $(this).attr('id');
console.log(id)
$('#' + id + '+*').toggle();
// toggle is not working when highlight function located in item in this specific chapter
});
// function 2 : highlight content
$('#monForm').submit(function(e) {
e.preventDefault();
console.log('submitted')
// clear form
var str = $('#valeurForm').val();
$('#valeurForm').val("");
console.log(str);
// highlight
var strCut = str.split(' ');
for (i = 0; i < strCut.length; i++) {
// grey chapter where the word is located
$("div[class='chapter']:contains(" + strCut[i] + ")").css("color", "#929aab");
// and highlight in red specific word
// but i want to highlight all occurences of the word in this chapter ? how can I define index d ?
$("div[class='chapter']:contains(" + strCut[i] + ")").each(function(d) {
$(this).html($(this).html().replace(strCut[i], '<font color="red">$&</font>'));
});
};
});
<head>
<meta charset="utf-8">
<style>
.content {
display: none;
}
</style>
</head>
<body>
<form name="search" id="monForm">
<input type="text" id="valeurForm">
</form>
<div class="chapter">
chapter 1
<button type="button" id="chapter1">Display content</button>
<div class="content">
content chapter1
</div>
</div>
<br>
<div class="chapter">
chapter 2
<button type="button" id="chapter2">Display content</button>
<div class="content">
content chapter2
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- jQuery est inclus ! -->
</body>
The problem was your $(this).html(). The .replace that you did removes the event listener of your button, because it modifies the DOM. Instead of getting the whole .html(), I did it with .children(), and then replaced just the text of it.
About replacing all the occurrences of the chapter word, you could use a Regular Expression. Using a string will replace just the first occurrence of the string. With the regular expression you can replace all of them.
// function 1 : toggle content when clicking the button
$(".chapter button").click(function(f) { //live deprecated to be replaced
f.preventDefault();
var id = $(this).attr('id');
$('#' + id + '+*').closest('.content').toggle();
// toggle is not working when highlight function located in item in this specific chapter
});
// function 2 : highlight content
$('#monForm').submit(function(e) {
e.preventDefault();
console.log('submitted')
// clear form
var str = $('#valeurForm').val();
$('#valeurForm').val("");
// highlight
var strCut = str.split(' ');
for (i = 0; i < strCut.length; i++) {
// grey chapter where the word is located
$("div[class='chapter']:contains(" + strCut[i] + ")").css("color", "#929aab");
// and highlight in red specific word
$("div[class='chapter']:contains(" + strCut[i] + ")").each(function(d) {
var regex = new RegExp(strCut[i],"g")
$(this).children().each(function (index,element) {
const text = $(element).html().replace(regex,'<font color="red">$&</font>')
$(element).html(text)
})
});
};
});
<head>
<meta charset="utf-8">
<style>
.content {
display: none;
}
</style>
</head>
<body>
<form name="search" id="monForm">
<input type="text" id="valeurForm">
</form>
<div class="chapter">
chapter 1
<button type="button" id="chapter1">Display content</button>
<div class="content">
content chapter1 and the second ocurrence of chapter also highlighted
</div>
</div>
<br>
<div class="chapter">
chapter 2
<button type="button" id="chapter2">Display content</button>
<div class="content">
content chapter2
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- jQuery est inclus ! -->
</body>
EDIT
I wasn't clear enough about the errors, sorry, and I've noticed the right solution.
The point is that, instead of modifying the parent element, I've changed the text of the childrens. When you change the whole html, you remove the listener of your buttons when you add it again to the html, and that's why isn't possible to toggle the divs.
I want to hide my bootstrap alert if it is empty. It hide correctly when page load, problem is when I do a push who insert data into div, it don´t show alert and it keep with display = none
HTML
<div id="a1" class="alert alert-success">
<div id="discussion"></div>
</div>
JS:
<script type="text/javascript">
hideAlert("a1");
function hideAlert(id) {
var text = $('#' + id + '#discussion').text();
console.log(text.length);
if (text.length <= 0)
$('#' + id).hide();
}
</script>
Edit
I try it using input event , it occurs same. It hide but it don't show when get value
JS:
<script type="text/javascript">
$('#discussion').keyup(function () {
// If value is not empty
if ($(this).val().length == 0) {
// Hide the element
$('#a1').hide();
} else {
// Otherwise show it
$('#a1').show();
}
}).keyup();
</script>
Your selector must be #a1 #discussion no #a1#discussion.So:
Change :
$('#' + id + '#discussion')
To:
$('#' + id + ' #discussion')
^-----------------
hideAlert("a1");
function hideAlert(id) {
var text = $('#' + id + ' #discussion').text();
console.log(text.length);
if (text.length <= 0)
$('#' + id).hide();
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="a1" class="alert alert-success">
<div id="discussion"></div>
</div>
After Update your question:
setInterval(function(){ hideAlert("a1"); }, 3000);
function hideAlert(id) {
var text = $('#' + id + ' #discussion').text();
if (text.length <= 0)
$('#' + id).hide();
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="a1" class="alert alert-success">
<div id="discussion" contenteditable="true">Some Text...</div>
</div>
Note : Remove text in div and see result
Why not try using the :empty css pseudo-class like this:
CSS
#discussion{
display: block;
}
#discussion:empty{
display: none;
}
HTML
<div id="discussion" class="alert alert-success"></div>
Note: The beginning and closing tags should be next to each other for the pseudo-class to work (like the beginning and closing div tags next to each other without any line breaks or space in the html shown above).
I have an element that contains the discount of a product
<div class="discount_discountAmount">
<div id="mydiscouttext" class="discouttext">0
<span class="price_percent">%</span>
</div>
</div>
I want, if the element with id="mydiscouttext" equal to 0, addClass "hide".
I am looking for a solution with javascript.
Any idea?
I did something similar for another person, where I the table row had to be highlighted in the case of value in a cell being <=5. Please see if this helps you: https://codepen.io/nitinsuri/pen/WoqLzX
$(document).ready(function(){
$("table#book-list").find("td").each(function(){
var quantity = parseInt($.trim($(this).text()));
if(quantity <= 5){
$(this).parent("tr").addClass("low-quantity");
}
});
});
changes to:
<div class="discount_discountAmount">
<div id="mydiscouttext" class="discouttext">
<span class="value_percent">0</span>
<span class="price_percent">%</span>
</div>
</div>
and:
$(document).ready(function(){
var discouttext = $('#mydiscouttext span:first-child').html();
if(discouttext === '0')
$('.discount_discountAmount').hide();
});
if(!parseInt(document.querySelector("#mydiscouttext").innerText)){
document.querySelector("#mydiscouttext").style.display = "none";
}
this can be help
there, in plain Javascript,
var discount = document.getElementById('ammount').innerHTML;
console.log(discount);
if(parseInt(discount) <= 0 ) {
document.getElementsByClassName('discount_discountAmount')[0].classList.add("hide");
}
<div class="discount_discountAmount">
<div id="mydiscouttext" class="discouttext"><span id="ammount">0</span>
<span class="price_percent">%</span>
</div>
</div>
Also, i added a span to isolate the percentage amount. it's easy to deal with it then.
I would recommend to put it inside a span like the percent and try to put make a javascript like this
<div>
<span id="mydiscouttext">0</span>
<span>%</span>
</div>
<script>
$( document ).ready(function(){
var text = $("#mydiscouttext").html();
if(text == "0")
$("#mydiscouttext").hide();
});
</script>
I have a code
$(".showerPr").on('click', '.prototypeDiv',function(){
});
HTML looks like
<div class='showerPr' data-id='3'>
<div class='prototypeDiv' data-id='5'><div>
</div>
Is there some solution to get showerPr data-id and prototypeDiv data-id seperately?
somethink like
$(this).attr('data-id');
$(this).before().attr('data-id');
:-D thank you.
.showerPr isn't before() the .prototypeDiv element, it's the parent element
var proto = $(this).data('id');
var shower = $(this).parent().data('id');
$(".showerPr").on('click', '.prototypeDiv',function(){
var proto = $(this).data('id');
var shower = $(this).parent().data('id');
$('#result').html('prototypeDiv : ' + proto + '<br />' + 'showerPr : ' + shower)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='showerPr' data-id='3'>
<div class='prototypeDiv' data-id='5'>Click Me !!!<div>
</div>
<br/><br/>
<div id="result"></div>
#adeneo is right, .showerPr is the parent element. You may want to check the Traversing Methods for jQuery.
Here are the snippets.
$(".prototypeDiv").on('click', function(){
alert($(this).data('id'));
alert($(this).parent().data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='showerPr' data-id='3'>
<div class='prototypeDiv' data-id='5'>123<div>
</div>
I have next structure - there are 7 blocks:
<div class="blog-item">
<h2>...</h2>
<p>...</p>
<div class="jcomments-links">
<a class="readmore-link" href="..."></a>
</div>
</div>
I want to receive href of the inner link, delete its parent block with link and add a link inside block with class="blog-item" with the same href as deleted link...
I had wrote this:
<script>
jQuery(document).ready(function() {
jQuery(".blog-item a.readmore-link").each(function() {
var ahref = jQuery(this).attr("href");
jQuery(this).parent('.jcomments-links').remove();
jQuery(this).parent().closest('.blog-item').wrapInner(function () {
return "<a href='" + ahref + "'></a>"
});
});
});
</script>
But something wrong. There will not appear new link. Any help will be greatly appreciated. Thanks
Try this (run the snippet to see it work, and you'll have to use the inspector to see that the html is correct):
jQuery(document).ready(function ($) {
$(".blog-item a.readmore-link").each(function () {
var ahref = $(this).attr("href"),
$wrapItem = $(this).closest('.blog-item');
$(this).closest('.jcomments-links').remove();
$wrapItem.wrapInner('<a href="' + ahref + '"/>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="blog-item">
<h2>Heading</h2>
<p>Paragraph</p>
<div class="jcomments-links">
remove
<a class="readmore-link" href="http://www.example.com">example</a>
</div>
</div>
its because you are deleting $(this) when you remove the .parent('.jcomments-links') from the DOM, so the reference to add the <a> to the .blog-item has not reference when you say $(this).closest() cause there is no more $(this).
try this:
$(document).ready(function() {
$(".blog-item a.readmore-link").each(function () {
var ahref = $(this).attr("href");
$(this).closest('.blog-item').append("<a href='" + ahref + "'>This is my new link</a");
$(this).parent('.jcomments-links').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blog-item">
<h2>...</h2>
<p>...</p>
<div class="jcomments-links">
<a class="readmore-link" href="this-is-my-href-i-want">This is the Link woo woo</a>
</div>
</div>