Change html element nested inside a random html element with jquery - javascript

I have a JQuery function that randomly chooses a DIV in a page full of DIVs. I'm trying to modify the function so that it checks the length of the H3 tag nested in the random DIV. If the string inside the H3 tag is over 10 characters long (including whitespace), the function should truncate the string and replace the contents of the H3 with this new shorter string and display it.
Example:
(jquery)
if ($('#main').length !== 0) {
var new_item = $('#main div').eq(Math.floor(Math.random() * $('#main div').length));
new_item.css('display','block');
}
(html file)
<div id="main">
<div id="m1" style="display:none;">
<h3>Apples are red</h3>
</div>
<div id="m2" style="display:none;">
<h3>Oranges are orange</h3>
</div>
<div id="m3" style="display:none;">
<h3>Bananas are yellow</h3>
</div>
</div>
(desired output - what user sees if DIV#m2 is randomly selected)
Oranges ar

$(new_item).find('h3').text($(new_item).find('h3').text().substr(0,10));

You already have the code that gets the random div element. The part you want to add is fairly trivial:
var h3_item = new_item.children("h3");
h3_item.html(h3_item.html().substring(0, 10));

Related

Remove repeated after 1st occurrence

I'm trying to clean up the results presented on my HTML file with Jquery. I want to keep removing words that are repeated more than one time.
A quick example
Accents Australian
Accents English (RP)
Dance Hip Hop
Dance Jazz
It should be output as
Accents
Australian
English (RP)
Dance
Hip Hop
Jazz
My original HTML looks like this
<div role="list" class="skill-items">
<div role="listitem" class="skill-item">
<div class="skill-category">Accents</div>
<div>Australian</div>
</div>
<div role="listitem" class="skill-item">
<div class="skill-category">Accents</div>
<div>English (RP)</div>
</div>
<div role="listitem" class="skill-item">
<div class="skill-category">Dance</div>
<div>Hip Hop</div>
</div>
<div role="listitem" class="skill-item">
<div class="skill-category">Dance</div>
<div>Jaz</div>
</div>
</div>
I tried my best but I'm not landing in a good place
$('.skill-category').text(function(index, oldText) {
return oldText.replace($(this).parent().next().find('.skill-category').text(), '');
})
Any suggestion?
Please check below working code:
const category = [...document.querySelectorAll('.skill-item > .skill-category')];
const texts = new Set(category.map(x => x.innerHTML));
category.forEach(category => {
if(texts.has(category.innerHTML)){
texts.delete(category.innerHTML);
}
else{
category.remove()
}
})
As per you question and shared HTML above is the working code for the same and if you add more similar things it will help.
Please let me know if you find any issues
Your question can be broken into two problems:
You want to group the elements with the same value for .skill-category
You want to change <div> elements into a list.
Grouping the elements could by done like so:
For every category, take a look at the previous element.
Does it contain the same category? If not, then continue to the next category.
If so, take everything after .skill-category (in your example HTML, that's a single <div>. Cut-and-paste it at the end of the aforementioned previous element.
For the second problem:
Changing an element (<div> to <li>) is not possible. You can create a new <li> and move what's inside the <div> into it. Of course, you'll need a <ul> that wraps the <li>s as well.
Take the .skill-category elements
Find all the content that follows the category (in your case, 1+ <div> elements)
Put the contents of the matched elements into a new <li>.
Put all the <li>s of a single category into a <ul>.
Remove the matched elements (in your case, the <div>(s)) since we've moved all their content to a different node. They're now empty tags and useless.
Put the <ul> after the .skill-category.
// Grouping the results.
$('.skill-category').each(function() {
// Get the previous .skill-item and find the category.
var prev = $(this).parent().prev('.skill-item').find('.skill-category');
// Check if the previous category === this category.
var same = !!(prev.length && prev.text() === $(this).text());
if (!same) {
return; // Do nothing.
}
// Take every element after the category and move it to the
// previous .skill-item.
prev.after($(this).nextAll());
// Then remove the now-empty category.
// All content has been moved to the previous element, after all.
$(this).parent().remove();
});
// Wrapping the contents of a category in a list.
$('.skill-category').each(function() {
var list = $('<ul></ul');
// Find everything after the category.
$(this).nextAll().each(function() {
// Create a <li> and move the child elements to it.
// Then add the <li> to the <ul>.
$('<li></li>').append($(this).contents()).appendTo(list);
}).remove(); // remove the now empty elements.
// Add the list to current .skill-category.
$(this).append(list);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div role="list" class="skill-items">
<div role="listitem" class="skill-item">
<div class="skill-category">Accents</div>
<div>Australian</div>
</div>
<div role="listitem" class="skill-item">
<div class="skill-category">Accents</div>
<div>English (RP)</div>
</div>
<div role="listitem" class="skill-item">
<div class="skill-category">Dance</div>
<div>Hip Hop</div>
</div>
<div role="listitem" class="skill-item">
<div class="skill-category">Dance</div>
<div>Jaz</div>
</div>
</div>

Copy first character of string to another div jquery or javascript

Is it possible with jQuery or Javascript to copy the first character of a string that's user generated to another div?
As an example, the contact list on iPhone. The first letter of the contact name is used in the circle adjacent to the name.
With the correct snippet the output would be as follows, where 'First name, Last name' will be different.
<div class="initial">F</div>
<div class="name">First name, Last name</div>
<div class="initial">J</div>
<div class="name">John Smith</div>
I tried to get some ideas from these other posts:
How do I make the first letter of a string uppercase in JavaScript?
How can I get the first three letters of a string in JQuery?
Detect character in div and remove it Javascript or jQuery
However, I'm not sure where to start and how to output the result to the 'initial' div.
The simple way to do this is to provide a function to text() of the .initial elements which reads the first character from the sibling .name and returns it, like this:
$('.initial').text(function() {
return $(this).next('.name').text().slice(0, 1).toUpperCase();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="initial"></div>
<div class="name">Foo Bar</div>
<div class="initial"></div>
<div class="name">John Smith</div>
a vanilla JS solution i came up with:
https://jsfiddle.net/y0c9be6g/
<div class="initial"></div>
<div class="name">Bob Smith</div>
<div class="initial"></div>
<div class="name">Jim Halpert </div>
<div class="initial"></div>
<div class="name">Billy Baldwin</div>
<script>
var names = document.querySelectorAll(".name");
var initials = document.querySelectorAll(".initial");
function addInitial(item){
item.previousSibling.previousSibling.innerHTML = item.textContent.charAt(0);
}
names.forEach(addInitial);
</script>

Fill data into all of my spans

I have 8 spans, 4 of the spans with values retrieved from Database are visible when page loads. The other spans are in my own popup box, when a user clicks on the button to view the popup, the value from the spans that were visible needs to also be inside the spans within the popup box.
So I used a each() function with two classes, '.heart' is the class that has the first 4 spans which are visible when page loads. '.likes-count' is another class that has 4 spans within a popup box.
My aim is to assign whatever value is in the first 4 spans to the other spans within popup box.
Im currently stuck in the code below.
JS
$('.heart, .likes-count').each(function(i, element) {
var thisID = "#" + $(this).attr('id'); // '#like1', '#like2'
var getAgain = "." + $(thisID + " span").attr('class'); // .likeCount1
getAgain = $(getAgain).text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can iterate through the spans of your first div using jQuery's each. The callback function of each gives you an index parameter which you can use to select the corresponding indexed span of the other div.
$("#hearts span").each(function(index){
var text = $(this).text();
$("#likes span").eq(index).text( text );
});//each
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="hearts">
<span>12</span>
<span>24</span>
<span>36</span>
<span>48</span>
</div>
<div id="likes">
<span></span>
<span></span>
<span></span>
<span></span>
</div>
try this:
$('.heart').each(function(i) {
$('.likes-count:eq('+i+')').text($(this).text())
});
You can use callback function of .text() instead of using .each() to achieve this:
var heartspans = $("#hearts span");
$("#likes span").text(function(i,o){
return heartspans.eq(i).text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="hearts">
<span>12</span>
<span>24</span>
<span>36</span>
<span>48</span>
</div>
<div id="likes">
<span></span>
<span></span>
<span></span>
<span></span>
</div>

jQuery how to replace all contents of an element into another?

Say I have 3 elements like below with different html contents:
<div id='result1'> <p>One</p> </div>
<div id='result2'> <p>Two</p> </div>
<div id='result3'> <p>Three</p> </div>
How can I copy just contents within the div element to the next one so that the final result looks like this?
<div id='result1'> <p>New content</p> </div>
<div id='result2'> <p>One</p> </div>
<div id='result3'> <p>Two</p> </div>
There will be new content for replacement and the last content can be discarded.
To clarify, I'll have something like:
<div id='new'> <p>New content</p> </div>
where I want to grab '<p>New content</p>' as new content to use.
What do you think?
To push the content down, reverse the collection and set the HTML to the HTML of the previous one.
var elems = $($('[id^=result]').get().reverse());
elems.html(function(i) {
return elems.eq(i+1).html();
}).last().html('New Content');
FIDDLE
You can use .html() on the element you want to change the content. For accessing particular element you can use ID Selector (“#id”) with Child Selector (“parent > child”).
Live Demo
$('#result1 > p').html('New content');
Edit to move contents to next elements you can iterate through all elements and start assigning the context of second last to last, third last to second last and so on
Live Demo
elements = $('[id^=result] > p');
len = elements.length;
elements.each(function(idx, el){
if(idx == elements.length-1) return;
$('#result'+ (len-idx) + ' p').html($('#result' + (len-idx-1) + ' p').html());
});
$('#result1 > p').html('New content');
try JS fiddle
I am suggesting to add a Parent Grid and use jquery first() and last(), These controls will function like a queue.
$('#Pdiv').children().last().remove();
$('#Pdiv').first().prepend("<div id='new'> <p>I am New One</p></div>");
alert($('#Pdiv').children().first().html());

jQuery to check if ID value has a number

Is there a way in jQuery to check if an ID value (Ex. id="number1") contains a number?
The idea would be:
if (ID has a number which will come from a variable) then do something.
this is what I came up with so far but it only works with the first div:
$("#tabsstyle li a").bind("click", function () {
var numSlide = $(this).attr("rel");
if ($('#slidesContainer div').attr('id').match(numSlide) ) {
$('#slidesContainer div').fadeIn();
}
numSlide will store a number coming from one of the 'a' clicked and check that number will be included in the id value of '#slidesContainer div', once that checked then the right div will fadeIn.
HTML structure below:
<div id="slidesContainer">
<div id="n1" class="slide">
<h2>Web Development Tutorial</h2>
<p><button class="test">N1</button></p>
</div>
<div id="n2" class="slide">
<h2>Grunge Brushes, Anyone?</h2>
<p><button class="test">N2</button></p>
</div>
<div id="n3" class="slide">
<h2>How About Some Awesome Grunge Textures?</h2>
<p><button class="test">N3</button></p>
</div>
<div id="n4" class="slide">
<h2>'Tis the End, My Friend.</h2>
<p><button class="test">N4</button></p>
</div>
</div>
var id = $('#element').attr('id'); // #element will replace
// with your desired selector
id.match(/[0-9]/g)
Checking
if( id.match(/[0-9]/g) ) {
// do something
}
You can take a look at the following jquery plugin
https://github.com/jquery/globalize
That handles "numbers" a number can be an integer or a decimal, and a decimal number has different representations based on the culture :)
You can use javascript to build a function with test and a regular expression to check if a string contains a number.
function hasNumber(t){
//regular expression: /\d/g
return /\d/g.test(t);
}
And then use jQuery to check the value of the attribute id
alert (hasNumber($('#checkMe').attr('id')))

Categories