count no of spans of specific class within a dynamically generated div - javascript

Supposing I have a number of divs that are dynamically generated and contain text. Each of these divs have a unique id which is also dynamically generated, e.g.
<div id="abstract_12345"> ... text ...</div>
Now within those divs there are spans of a particular type that have been dynamically generated according to a regex, e.g. when the word "significant" is encountered it is tagged as
<span class="emphasis">significant</span>
This is being done via mark.js
What would be a suggestion for a javascript function to enable counting the spans within each div with the aim of placing the count value in an element associated with that div?

Using jQuery you can do:
$('div[id^="abstract_"]').each(function () {
var $this = $(this),
len = $this.find('span.emphasis').length;
console.log($this.attr('id'), len);
});
div {margin: 0 0 15px 0;}
span.emphasis {color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="abstract_12345"><span class="emphasis">Lorem ipsum</span> dolor sit amet, consectetur adipisicing elit. <span>Sapiente ipsam animi</span>, alias harum aut est unde voluptates repudiandae vel molestias <span class="emphasis">significant</span>, officia! Illum dolore pariatur sequi magnam minus, aliquid voluptate officia, <span>quaerat</span> sint quam <span class="emphasis">commodi</span>.</div>
<div id="abstract_12346">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente ipsam animi, alias harum aut est unde voluptates repudiandae vel molestias, officia! Illum dolore pariatur sequi magnam minus, aliquid voluptate officia, <span>quaerat</span> sint <span class="emphasis">quam commodi</span>.</div>

If you want to do using plain Javascript.
function myFunction() {
var i;
var x = document.querySelector("[id^=abstract_]").querySelectorAll("span");
for (i = 0; i < x.length.i++){
x[i].id = i;
}
}
This code will add id to each span as the index of the span inside the div with id=abstract_12345.

This should do the trick, if I understand your wish correctly.
$('id*="abstract_"').each(function() {
var amount = $(this).find('span.emphasis').length;
$(this).prepend(amount);
});

Related

how to use a queryselector on object HTMLInputElement

I am trying that when the text field has focus, the div is selected with the class:autocomplete, this is an example to understand my idea, in my real problem it is more complex. I simply need that once the element that has the focus is identified, select the nearest div with .autocomplete class on the same level, I want to get it this way. I know that in css I should use something like:
input ~ div.autocomplete
($event.target is input in my case)
but I don't know how to do it in this case. Thank you.
function fn_selectAutocompleteClass($event) {
console.log(($event.target));
}
.selectAutocomplete {
background: green;
}
<input id="text" type="text" onfocus="fn_selectAutocompleteClass(event)">
<i class="icon"></i>
<div class="autocomplete">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum itaque placeat, ad vel reprehenderit illo, harum nemo laudantium, dolorem unde aut distinctio! Consectetur vitae deleniti veritatis autem numquam officia eaque.</div>
In this case you can access the .autocomplete using the querySelectorAll on the target elements parent like below snippet. Get the 0th index as that will be the first element matching the selector query.
function fn_selectAutocompleteClass($event) {
console.log($event.target.parentNode.querySelectorAll('.autocomplete')[0]);
}
.selectAutocomplete {
background: green;
}
<input id="text" type="text" onfocus="fn_selectAutocompleteClass(event)">
<i class="icon"></i>
<div class="autocomplete">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum itaque placeat, ad vel reprehenderit illo, harum nemo laudantium, dolorem unde aut distinctio! Consectetur vitae deleniti veritatis autem numquam officia eaque.</div>
Hope this helps :)

How to create function that swaps divs with different ids?

I'm trying to create function in js to swap content of webpage using .style.display = "none" or "block" but the main problem is that there are few different divs with different id's for that. The main aim of doing this is chagning content after clicking specific buttons without loading new page. The biggest problem for me is creating script which will change "id"
independently of what id was before. Normally I could write all of id's one by one and just swap them but this is not the case. Content should be changed automatically so no matter what id was before it will replace for specific one after pressing button.
I have tried with querySelector in many ways by changing id with class, by using remove / set Attribute but none of these methods work for me. Im trying to write this fuction for 2 weeks and I don't have any ideas.
I'm worried that bootstrap classes may cause problem with this...
Can someone help me with this? Any tips?
This is my first post here so if I did something wrong, sorry for that.
I cannot paste here my code as everything is on my company laptop which I left when I was finish my job.
Here is an agnostic approach using no HTML ids or classes.
const container = document.querySelector('.container');
const buttons = container.querySelectorAll('button');
const divs = container.querySelectorAll(':scope > div');
function handleButtonClick() {
this.previousElementSibling.classList.toggle('hide');
}
buttons.forEach(button => {
button.addEventListener('click', handleButtonClick);
});
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 20px;
}
.hide {
display: none;
}
<div class="container">
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis sed, dicta quasi in blanditiis nam atque odio, nobis a. Eos incidunt debitis tenetur rerum, esse ratione quisquam possimus quasi nam.</p>
<button>Toggle Content</button>
</div>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis sed, dicta quasi in blanditiis nam atque odio, nobis a. Eos incidunt debitis tenetur rerum, esse ratione quisquam possimus quasi nam.</p>
<button>Toggle Content</button>
</div>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis sed, dicta quasi in blanditiis nam atque odio, nobis a. Eos incidunt debitis tenetur rerum, esse ratione quisquam possimus quasi nam.</p>
<button>Toggle Content</button>
</div>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis sed, dicta quasi in blanditiis nam atque odio, nobis a. Eos incidunt debitis tenetur rerum, esse ratione quisquam possimus quasi nam.</p>
<button>Toggle Content</button>
</div>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis sed, dicta quasi in blanditiis nam atque odio, nobis a. Eos incidunt debitis tenetur rerum, esse ratione quisquam possimus quasi nam.</p>
<button>Toggle Content</button>
</div>
</div>
jsFiddle

Toggling divs to fade in and out on click

Problem
I have two info boxes that are display:none when a user clicks the first span.highlight shows info box to the side aside.info. If the other span is clicked it shows the alternate second info box. However, clicking on the links a second time, doesn't fade them out/back in
Previously, I didn't have a fadeOut function and instead had bg-one and bg-two fade in and out, but you would still see the previous element before the other faded in, so I feel like the problem is with my if/else statement.
JSFiddle: http://jsfiddle.net/51haqmg3/4/ (scroll until you see two highlighted phrases)
scripts.js
/*-------------------------------------
HIGHLIGHT
--------------------------------------*/
$(".highlight").click(function() {
$(".highlight").removeClass("active"); // Remove active class from spans
$(".fa-plus-circle").show(); // Show the Font Awesome icon
$(this).addClass("active"); // Add an active class to span just
$(this).find(".fa-plus-circle").hide();
$(this).data("clicked", true);
var clicked = $(".highlight").data("clicked");
if (clicked) {
$(".bg-one").fadeOut(500, function() {
$(".bg-two").fadeIn(500);
});
} else {
$(".bg-two").fadeOut(500, function() {
$(".bg-one").fadeIn(500);
});
}
});
index.html
<aside class="info bg-one">
<div class="define">
<p class="background">Background One</p>
<img src="https://placeholdit.imgix.net/~text?txtsize=21&txt=224%C3%97148&w=224&h=148" alt="">
<p class="caption"></p>
<p class="hoarding"></p>
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam, laudantium, excepturi. Neque doloribus praesentium ad. Voluptates animi accusamus iusto laborum aperiam quis, eveniet architecto mollitia labore in laboriosam illum. Facilis.</li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum perspiciatis minus corporis expedita fugiat excepturi nostrum atque adipisci magnam deserunt, reprehenderit, a fugit, neque esse unde mollitia at nemo. Natus?</li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae quas nulla, voluptatem corrupti vel, maiores delectus fuga dolorum sint, nisi suscipit deleniti, velit? Debitis maxime, necessitatibus similique saepe vel nisi!</li>
</ul>
</div><!-- /.define -->
</aside>
If you just want to detect if the first element was clicked or if it was the second one and then fade out and fade in the corresponding info boxes you could do this:
http://jsfiddle.net/so14L57w/
All I changed was the bool variable to determine which background to switch to:
var fadeOne = $(".highlight").index(this) == 0;
This isn't a great solution though since it won't scale beyond your 2 elements. However you could switch on the $(".highlight") index and load the correct background that way for more than 2 elements.
You're always setting them to true instead of toggling them on each click.
Fix this line:
$(this).data("clicked", true);
to something like:
$(this).data("clicked", !$(this).data("clicked"));
Also the whole block above it:
$(".highlight").removeClass("active"); // Remove active class from spans
$(".fa-plus-circle").show(); // Show the Font Awesome icon
$(this).addClass("active"); // Add an active class to span just
$(this).find(".fa-plus-circle").hide();
should be in the conditional in order for you to be able to cancel their action when clicked is false.

How to remove HTML element dynamically when others are been removed using jquery

I have this html code here:
<div class="container">
<section>
<header class="date">May 2014</header>
<article>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus, dolorem, laborum non illum voluptate vitae quibusdam impedit</article>
<article>Repellendus, dolorem, laborum non illum voluptate vitae quibusdam impedit aperiam placeat minus ratione mollitia expedita tempore reprehenderit maxime.</article>
<article>ratione mollitia expedita tempore reprehenderit maxime.</article>
Remove Article
</section>
<section>
<header class="date">March 2014</header>
<article>Repellendus, dolorem, laborum non illum voluptate vitae quibusdam impedit aperiam placeat minus ratione mollitia expedita tempore reprehenderit maxime unde quas beatae maiores.
</article>
Remove Article
</section>
<section>
<header class="date">April 2014</header>
<article>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</article>
<article>Repellendus, dolorem, laborum non illum voluptate vitae quibusdam impedit aperiam placeat minus ratione mollitia expedita tempore reprehenderit maxime unde quas beatae maiores.
</article>
Remove Article
</section>
</div>
When I click on 'Remove Article" link i should remove one of the article above it. I've got that.
Now what i'm trying to accomplish here is, when I remove all articles 'one by one' that belongs to specific section I need automaticly to have the header 'date' and the link 'Remove Article' to be removed completely.
I have tried different ways, but still I can see both header and link, but when I refresh page they are gone.
I think I got you. Do you want to remove articles one by one then if there's no more remove the whole section? If so, this should work:
$('a').on('click', function (e) {
e.preventDefault();
var $section = $(this).closest('section'),
$articles = $section.find('article');
$articles.last().remove();
// $articles.length will not be one less just because we removed
// an item, so just checking for 1 here is the same as checking
// if it's empty.
if ($articles.length === 1) {
$section.remove();
}
});
have you tried binding this.parentElement.remove() to the a elements in your html? It will remove the entire section.
$('.container a').click(function(){
this.parentNode.remove()
}
$('section a').on('click', function(e) {
e.preventDefault();
var self = $(this);
var articles = self.siblings('article');
if (articles.length > 1) {
articles.last().remove();
}
else {
self.parent().remove();
}
})
JSFiddle
UPDATE: removes each article until only one is left in a section, then removes last article and section. Thanks #Barmar for pointing out my error.
$('body').on('click', '.container a', function (e) {
e.preventDefault();
var articleLength = $(this).closest('section').find('article').length;
if (1 != articleLength) {
$(this).closest('section').find('article:last').remove();
} else {
$(this).closest('section').remove();
}
});

Dynamically and completely fill a div with placeholder text in javascript

I would like to Fill a div with placeholder text.
I have a div that is 100% width+height. Due to many form factors this height and width will be changing based on the users resolution. How can i dynamically fill that div with lorem ipsum. Also how would i recalculate if window sizes changes? I know i could manually do this with copy paste and overflow hidden but I would rather achieve this in javascript
JSFiddle
css
html,body {
/*background:#edecec;*/
height: 100%;
}
.block-text{
text-align: justify;
font-size: 8px;
font-color: rgba(88,89,91, 1);
font-family: georgia;
line-height: 7px;
}
html
<div class="block-text">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore, eius, ab, molestiae praesentium hic quia quaerat culpa quas consectetur dolor veritatis vel voluptas minus laborum minima quis dolorum necessitatibus tempora.
</p>
</div>
http://jsfiddle.net/h54tP/1/
var bool = true;
var maxHeight = $('.block-text').height();
do {
$('.container').append("<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore, eius, ab, molestiae praesentium hic quia quaerat culpa quas consectetur dolor veritatis vel voluptas minus laborum minima quis dolorum necessitatibus tempora. </p>");
if ($('.container').height() > maxHeight) bool = false;
} while (bool);
Here, as described in my comment. One wrapping element insinde your text box, the block-text set to 100% height and a small while loop do the trick.
Small note: This will not do anything when the window is resized. For that, however, you could just call that entire code inside a window-size-change function.
Also, this allows the text to be slightly larger than the screen. If you want it slightly smaller instead, just do
$('.container').children().last().hide();
in the "if"-clause.
I realize you wanted to solve this with javascript, but have you considered using css psuedo-elements with content? If this is just for placeholder text as you develop I think it will do what you want without having to add a bunch of javascript and fiddle with resize events.
.block-text>p:after {
content: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore, eius, ab, molestiae praesentium hic quia quaerat culpa quas consectetur dolor veritatis vel voluptas minus laborum minima quis dolorum necessitatibus tempora.';
}

Categories

Resources