Use of Jquery .not() in a variable [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Getting text within element excluding decendants
I have the following function:
function initCBox(){
CB_Init();
var img1 = $(select.currentImg).attr('src');
var label = $(select.currentImg).attr('alt');
var desc = $('.item.active .caption').not($('.description')).text();
CB_Open('href=' + img1 + ',,title=' + label + ',,comment=' + desc +'');
}
with the following html:
<div class="item" title="Light" href="Light.jpg" >
<img class="content" alt="Amber Light" src="slides/Light.jpg"/>
<div class="caption">Light
<ul class="icon">
<li class="ui-state-default ui-corner-all" title="More Info">
<div class="description ui-icon ui-icon-comment">
<div class="description_holder" style="display:none">Amber Light
<br />Enter Text or HTML Here</div>
</div> </li>
</ul>
</div></div>
I want my var = desc to only show the text in the class "caption", not anything in the <ul class="icon"> ( for simplicity, I only include one <li> item but I have others in the <ul>). Need help with my excluding all but the caption text. Hope I haven't been too confusing!

You can do a string find and replace:
var desc = $('.caption').text(), // The caption and stuff you don't want
noWant = $('.icon').text(); // Only stuff you don't want
desc = desc.replace(noWant,""); // Find stuff you don't want and replace w ""
The advantage if this way over excluding descendants, is that it will grab the entire text of your description even if includes <span>s, <strong>s, etc.

Related

Add svg fill patterns dynamically via JavaScript [duplicate]

When prepending or appending to an element, it literally puts the text and doesn't compile in HTML:
var banner ={
'Format': '90x120cm',
'Value': 35
};
// var premium = { key: values };
function defineProduct(data) {
var item = $('span.tooltip')[0];
console.log($('span.tooltip'));
for(var keys in data){
console.log(keys);
item.append('<div class="item"><div class="left">'+keys+':</div><div class="right ">'+data[keys]+'</div></div>');
}
}
defineProduct(banner);
HTML:
<div class="three-columns">
<div class="col">
<div class="image-holder">
<a href='' id="premium" class="tooltips">
<img src="" class="premium-img" width="85px" height="79px">
<p class="description">Cartão <br><span style="color: #ffc600;" class="different">premium</span></p>
<span class="tooltip"></span>
</a>
</div>
<!-- Same thing from above different description -->
<!-- ditto -->
</div>
Output:
What have I tried/used:
.get();
.prepend(string);
.html(string);
.text(string); <– I don't know why, but I did
document.createTextNode(string);
set a variable which contains HTML tags strings and set to one of the previous attempts
And the reason I used .get() is because I have more than one object that are equivalent to the quantity of their elements, in this case, I have 3. So, for every append, I have different information. E.g.: .get(0), .get(1), etc
Instead of
item.append....
you can use:
item.insertAdjacentHTML('beforeend',....
insertAdjacentHTML: parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.
var banner = {
'Format': '90x120cm',
'Value': 35
};
function defineProduct(data) {
var item = $('span.tooltip')[0];
//console.log($('span.tooltip'));
for (var keys in data) {
//console.log(keys);
item.insertAdjacentHTML('beforeend', '<div class="item"><div class="left">' + keys + ':</div><div class="right ">' + data[keys] + '</div></div>');
}
}
defineProduct(banner);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="three-columns">
<div class="col">
<div class="image-holder">
<a href='' id="premium" class="tooltips">
<img src="" class="premium-img" width="85px" height="79px">
<p class="description">Cartão <br><span style="color: #ffc600;" class="different">premium</span></p>
<span class="tooltip"></span>
</a>
</div>
<!-- Same thing from above different description -->
<!-- ditto -->
</div>
</div>
You're using ParentNode.append to append a literal DOMString which is appended as a text node instead of jQuery#append here:
var item = $('span.tooltip')[0];
The [0] access the underlying DOM element in the jQuery object. Remove the [0] to use jQuery methods (or eq(0) for the first element in the selection collection as a jQuery object) on it or use Node.appendChild.
[0] needs to be removed from $('span.tooltip')[0] . It is trying to access first child of ".tooltip" span which is not available in DOM.

Numbered images selector

Good day!
First of all, I don't what is the right name or title for my question but that's what I think what I needed.
how can I make an image selector with numbered function like the image below? I am using html and jquery to select images but I don't know how to put and ordered numbers when selecting an images. My codes are like...
HTML:
<div class="photoList">
<label class="singlePhotoWrap relative">
<img src="images/previewDefaultImg.png" class="photo" alt="Image">
<img src="images/numberedIco.png" class="absolute numberedIcon" alt="Check Icon">
<span class="photoCounter">1</span>
<input type="checkbox" name="photoSelector" class="hidden" autocomplete="off">
</label>
...
Javascript:
$(document).ready(function(e){
$(".singlePhotoWrap").click(function() {
var current = document.getElementById("photoSelectedCounter").value;
if ($(this).find('input[name=photoSelector]:checked')){
var totalAdd = parseFloat(current) + .5;
$('#photoSelectedCounter').val(totalAdd);
$(this).find(".photoCounter").text(totalAdd);
}
if ($(this).find('input[name=photoSelector]:unchecked')) {
var totalAdd = parseFloat(current) - .5;
$('#photoSelectedCounter').val(totalAdd);
$(this).find(".photoCounter").text(totalAdd);
}
});
});
My javascript codes always returning as checked. It always adding to my span.
Here's the screenshot:
Numbered Image Selector Screenshot
How can I do that using javascript or jquery?

how to change all elements id in div child [duplicate]

This question already has answers here:
jQuery selector for id starts with specific text [duplicate]
(4 answers)
Closed 6 years ago.
How I can change and add something to all ids in div child elements that have something like bi_ in his first. like this example:
<script>
var opts = '1';
$('.mm > #bi_name').attr('id', 'bi_name_'+opts);
$('.mm > #bi_email').attr('id', 'bi_email_'+opts);
$('.mm > #bi_expire').attr('id', 'bi_expire_'+opts);
$('.ss > #bi_ohhh').attr('id', 'bi_ohhh_'+opts);
$('.ss > #bi_bala').attr('id', 'bi_bala_'+opts);
$('.ss > #bi_ola').attr('id', 'bi_ola_'+opts);
.....
</script>
<div id="lol" class="mm">
<!-----I want to change all id below----->
<div id="profile">
<div class="about text-center">
<h1 id="bi_name">Banned player name</h1> //change and this id="bi_name" to id="bi_name_1"
</div>
<ul class="personal-info">
<li><label><i class="fa fa-envelope fa-fw fa-lg"></i> Email</label><span id="bi_email">EMAIL</span></li> //change and this id="bi_email" to id="bi_email_1"
<li><label><i class="fa fa-calendar fa-fw fa-lg"></i> Expire Time</label>
<span>
EXPIRE TIME //change and this id="bi_expire" to id="bi_expire_1"
</span>
</li>
</ul>
</div>
<div id="content" class="ss">
.....
</div>
<div id="gallery" class="gg">
....
</div>
<!-----I want to change all id above----->
</div>
You can use target all the elements using Attribute Starts With Selector [name^=”value”] then use .attr(attributeName, fn) to set the id
var opts = '1';
$('.mm [id^=bi_]').attr('id', function(_, val){
return val + '_' + opts;
});

Mass replace of elements [duplicate]

This question already has answers here:
Recursively change element type with jQuery, why it's partially working?
(2 answers)
Closed 7 years ago.
I'm trying to replace all the child elements in a certain element to DIVs.
I have the following structure:
<div id="wrapper">
<span>
<span>
<span>
<span></span>
<span></span>
</span>
</span>
</span>
</div>
I've tried replaceElements($('#wrapper')):
function replaceElements($element){
var children = $element.find("*");
var current;
for(var i=0; i<children.length; i++){
current = $(children[i]);
current.replaceWith("<div>" + current.html() + "</div>");
}
}
However this doesn't work because when it tries to change the N+1 element it all ready doesn't exist because it was replaced when doing the Nth element. N+1 is a descendant of N and thus is being changed when changing the .html() of N. Preserving element attributes is not an issue here.
How can I change all the child SPANs into DIVs, please?
You should not use the html content in the replaced element, instead need to add the dom elements to it
function replaceElements($element) {
$element.find("*").replaceWith(function() {
return $('<div></div>', {
html: this.childNodes
});
})
}
replaceElements($('#wrapper'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="wrapper">
<span>1
<span>2
<span>3
<span>4</span>
<span>5</span>
</span>
</span>
</span>
</div>
Note: No attributes of the elements will be copied

Grabbing number from selected class based on string match

I need to grab the number between [ and ] within the selected class of an li list, and store the number in a variable. I've tried the following, but I'm missing something. I'm not sure of the regex required to look between brackets and grab a string.
Javascript
var assetID = $(".selected:contains('on-air-date').find('[]');
HTML
<ul id="asset-list" class="expandable selectable normal" style="height: 671px;">
<li class="selected">
<div class="thumb">
<a href="/content/assets/750">
<img src="https://www.google.com/images/srpr/logo11w.png">
</a>
</div>
<div class="title">
<div>
<strong>Title of story</strong>
<br>
<span class="on-air-date">
On air: 10/28/14 05:30:00pm
[750]
</span>
<br>
<span class="blue radius label">Staging</span>
<span class="green radius label">Live</span>
</div>
</div>
</li>
<li>
<div class="thumb">
<a href="/content/assets/4200">
<img src="https://www.google.com/images/srpr/logo11w.png">
</a>
</div>
<div class="title">
<div>
<strong>Another story title</strong>
<br>
<span class="on-air-date">
On air: 12/10/14 02:09:18pm
[4200]
</span>
<br>
<span class="blue radius label">type label</span>
</div>
</div>
</li>
<li>
<div class="thumb">
<a href="/content/assets/4201">
<img src="https://www.google.com/images/srpr/logo11w.png">
</a>
</div>
<div class="title">
<div>
<strong>Yet another story title</strong>
<br>
<span class="on-air-date">
On air: 12/10/14 02:09:18pm
[4201]
</span>
<br>
<span class="blue radius label">type label</span>
</div>
</div>
</li>
</ul>
JSFiddle: link
Your current code is invalid, as :contains is used to look for a text value within an element, not a class. You need to use find() and text() to retrieve the value in the element. From there you can use a regular expression to extract the value in the braces. Try this:
var selectedAirDateText = $('.selected').find('.on-air-date').text();
var matches = /\[(.+)\]/gi.exec(selectedAirDateText);
console.log(matches[1]); // = '750'
Example fiddle
A regular expression can help you get the number as follows:
var num = $('.selected span.on-air-date').text().replace(/[^\[]*\[(\d+)\].*/,'$1');
Demo
:contains('on-air-date') not valid, you cannot use contains to access the child elements with the specified class. Also .find('[]') not valid. The following code worked for me:
$('.selected').click(function () {
var assetID = $(this).find('.on-air-date').text().split('[')[1].replace(']', '');
//this first splits the text into two by '['
//then we get the second half by [1]
//finally we remove the last character ']' by using .replace
alert(assetID);
})
Demo: https://jsfiddle.net/k3keq3vL/1/
You'll need to first get the single item you need or run an $.each to get all in the page.
//run the each statement
$(".on-air-date").each(function(index,value) {
//set the string (str) variable to the value's text which is inside the <span>
var str = $(value).text();
// match the string with [ ] with anything inside. and then remove the last ]. Then take the substring of the content after the [
var value = str.match(/\[(.*?)\]/g)[0].replace(/\]/g,'').substring(1,str.length-1));
});
http://jsfiddle.net/k3keq3vL/8/
Open your console to see the list of numbers returned in the console.log of the string match and substring

Categories